-
-
Notifications
You must be signed in to change notification settings - Fork 534
/
vite-svg-loader.js
59 lines (45 loc) · 1.33 KB
/
vite-svg-loader.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
const fs = require('fs').promises
const { compileTemplate } = require('@vue/compiler-sfc')
const { optimize: optimizeSvg } = require('svgo')
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) {
console.warn('\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
}
const { code } = compileTemplate({
id: JSON.stringify(id),
source: svg,
filename: path,
transformAssetUrls: false
})
return `${code}\nexport default { render: render }`
}
}
}
module.exports.default = module.exports