-
-
Notifications
You must be signed in to change notification settings - Fork 428
/
Copy pathindex.js
67 lines (59 loc) · 1.87 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
58
59
60
61
62
63
64
65
66
67
import { getOptions } from 'loader-utils'
import { transform as babelTransform, createConfigItem } from '@babel/core'
import convert from '@svgr/core'
import svgo from '@svgr/plugin-svgo'
import jsx from '@svgr/plugin-jsx'
import presetReact from '@babel/preset-react'
import presetEnv from '@babel/preset-env'
import pluginTransformReactConstantElements from '@babel/plugin-transform-react-constant-elements'
const babelOptions = {
babelrc: false,
configFile: false,
presets: [
createConfigItem(presetReact, { type: 'preset' }),
createConfigItem([presetEnv, { modules: false }], { type: 'preset' }),
],
plugins: [createConfigItem(pluginTransformReactConstantElements)],
}
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
? `export default ${exportMatches[1]}`
: null
const pBabelTransform = async jsCode =>
new Promise((resolve, reject) => {
babelTransform(jsCode, babelOptions, (err, result) => {
if (err) reject(err)
else resolve(result.code)
})
})
const tranformSvg = svg =>
convert(svg, options, {
caller: {
name: '@svgr/webpack',
previousExport,
defaultPlugins: [svgo, jsx],
},
filePath: this.resourcePath,
})
.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