-
-
Notifications
You must be signed in to change notification settings - Fork 411
/
index.js
57 lines (50 loc) 路 1.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { getOptions } from 'loader-utils'
import { transform as babelTransform } from '@babel/core'
import convert from '@svgr/core'
function svgrLoader(source) {
const callback = this.async()
const { babel = true, ...options } = getOptions(this) || {}
const readSvg = () =>
new Promise((resolve, reject) => {
this.fs.readFile(this.resourcePath, (err, result) => {
if (err) reject(err)
resolve(result)
})
})
const exportMatches = source
.toString('utf-8')
.match(/^module.exports\s*=\s*(.*)/)
const previousExport = exportMatches ? exportMatches[1] : null
const pBabelTransform = async jsCode =>
new Promise((resolve, reject) => {
babelTransform(
jsCode,
{
babelrc: false,
presets: [
'@babel/preset-react',
['@babel/preset-env', { modules: false }],
],
plugins: [
'@babel/plugin-transform-react-constant-elements',
'@babel/plugin-proposal-object-rest-spread',
],
},
(err, result) => {
if (err) reject(err)
else resolve(result.code)
},
)
})
const tranformSvg = svg =>
convert(svg, options, { webpack: { previousExport } })
.then(jsCode => (babel ? pBabelTransform(jsCode) : jsCode))
.then(result => callback(null, result))
.catch(err => callback(err))
if (exportMatches) {
readSvg().then(tranformSvg)
} else {
tranformSvg(source)
}
}
export default svgrLoader