-
-
Notifications
You must be signed in to change notification settings - Fork 425
/
Copy pathindex.js
66 lines (55 loc) · 1.78 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
import fs from 'fs'
import convert from '@svgr/core'
import { createFilter } from 'rollup-pluginutils'
import { transformAsync, createConfigItem } from '@babel/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 svgrPlugin(options = {}) {
const filter = createFilter(options.include || '**/*.svg', options.exclude)
const { babel = true } = options
return {
name: 'svgr',
async transform(data, id) {
if (!filter(id)) return null
if (id.slice(-4) !== '.svg') return null
const load = fs.readFileSync(id, 'utf8')
const exportMatches =
data.match(/^module.exports\s*=\s*(.*)/) ||
data.match(/export\sdefault\s(.*)/)
const previousExport = exportMatches ? data : null
const ast = {
type: 'Program',
sourceType: 'module',
start: 0,
end: null,
body: [],
}
const jsCode = await convert(load, options, {
filePath: id,
caller: {
name: '@svgr/rollup',
previousExport,
defaultPlugins: [svgo, jsx],
},
})
if (babel) {
const { code } = await transformAsync(jsCode, babelOptions)
return { code, map: { mappings: '' } }
}
return { ast, code: jsCode, map: { mappings: '' } }
},
}
}
export default svgrPlugin