Skip to content

Commit

Permalink
Small refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
gkatsanos committed May 19, 2023
1 parent 5fc7c4d commit d3c6035
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions index.js
Expand Up @@ -2,17 +2,15 @@ const fs = require('fs').promises
const { compileTemplate } = require('vue/compiler-sfc')
const { optimize: optimizeSvg } = require('svgo')

module.exports = function svgLoader (options = {}) {
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)) {
async load(id) {
if (!id.endsWith('.svg')) {
return
}

Expand All @@ -29,7 +27,10 @@ module.exports = function svgLoader (options = {}) {
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`)
console.warn(
'\n',
`${id} couldn't be loaded by vite-svg-loader, fallback to default loader`
)
return
}

Expand All @@ -40,22 +41,24 @@ module.exports = function svgLoader (options = {}) {
if (svgo !== false && query !== 'skipsvgo') {
svg = optimizeSvg(svg, {
...svgoConfig,
path
path,
}).data
}

// To prevent compileTemplate from removing the style tag
svg = svg.replace(/<style/g, '<component is="style"').replace(/<\/style/g, '</component')
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
transformAssetUrls: false,
})

return `${code}\nexport default { render: render }`
}
},
}
}

Expand Down

0 comments on commit d3c6035

Please sign in to comment.