-
-
Notifications
You must be signed in to change notification settings - Fork 425
/
Copy pathindex.ts
93 lines (83 loc) · 2.48 KB
/
index.ts
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import * as fs from 'fs'
import { transform, Config } from '@svgr/core'
import { createFilter, CreateFilter } from '@rollup/pluginutils'
import { transformAsync, createConfigItem } from '@babel/core'
import svgo from '@svgr/plugin-svgo'
import jsx from '@svgr/plugin-jsx'
// @ts-ignore
import presetReact from '@babel/preset-react'
// @ts-ignore
import presetEnv from '@babel/preset-env'
// @ts-ignore
import presetTS from '@babel/preset-typescript'
// @ts-ignore
import pluginTransformReactConstantElements from '@babel/plugin-transform-react-constant-elements'
import type { PluginImpl } from 'rollup'
const babelOptions = {
babelrc: false,
configFile: false,
presets: [
createConfigItem(presetReact, { type: 'preset' }),
createConfigItem([presetEnv, { modules: false }], { type: 'preset' }),
],
plugins: [createConfigItem(pluginTransformReactConstantElements)],
}
const typeScriptBabelOptions = {
...babelOptions,
presets: [
...babelOptions.presets,
createConfigItem(
[presetTS, { allowNamespaces: true, allExtensions: true, isTSX: true }],
{ type: 'preset' },
),
],
}
export interface Options extends Config {
include?: Parameters<CreateFilter>[0]
exclude?: Parameters<CreateFilter>[1]
babel?: boolean
}
const plugin: PluginImpl<Options> = (options = {}) => {
const EXPORT_REGEX = /(module\.exports *= *|export default)/
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 previousExport = EXPORT_REGEX.test(data) ? data : null
const jsCode = await transform(load, options, {
filePath: id,
caller: {
name: '@svgr/rollup',
previousExport,
defaultPlugins: [svgo, jsx],
},
})
if (babel) {
const result = await transformAsync(
jsCode,
options.typescript ? typeScriptBabelOptions : babelOptions,
)
if (!result?.code) {
throw new Error(`Error while transforming using Babel`)
}
return { code: result.code, map: null }
}
return {
ast: {
type: 'Program',
start: 0,
end: 0,
sourceType: 'module',
body: [],
},
code: jsCode,
map: null,
}
},
}
}
export default plugin