-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
index.js
66 lines (49 loc) · 1.55 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
const fs = require('fs').promises
const { compileTemplate } = require('vue/compiler-sfc')
const { optimize: optimizeSvg } = require('svgo')
const _debug = require('debug')
const debug = _debug('vite-svg-loader')
module.exports = function svgLoader (options = {}) {
const { svgoConfig, svgo, defaultImport } = options
const svgRegex = /\.svg(\?(raw|component|skipsvgo))?$/
return {
name: 'svg-loader',
enforce: 'pre',
async load (id) {
if (!id.match(svgRegex)) {
return
}
const [path, query] = id.split('?', 2)
const importType = query || defaultImport
if (importType === 'url') {
return // Use default svg loader
}
let svg
try {
svg = await fs.readFile(path, 'utf-8')
} catch (ex) {
debug('\n', `${id} couldn't be loaded by vite-svg-loader, fallback to default loader`)
return
}
if (importType === 'raw') {
return `export default ${JSON.stringify(svg)}`
}
if (svgo !== false && query !== 'skipsvgo') {
svg = optimizeSvg(svg, {
...svgoConfig,
path
}).data
}
// To prevent compileTemplate from removing the style tag
svg = svg.replace(/<style/g, '<component is="style"').replace(/<\/style/g, '</component')
const { code } = compileTemplate({
id: JSON.stringify(id),
source: svg,
filename: path,
transformAssetUrls: false
})
return `${code}\nexport default { render: render }`
}
}
}
module.exports.default = module.exports