Skip to content

Commit

Permalink
providing alias for component
Browse files Browse the repository at this point in the history
  • Loading branch information
gkatsanos committed May 18, 2023
1 parent 8a2e17d commit 5191860
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
4 changes: 4 additions & 0 deletions .prettierrc
@@ -0,0 +1,4 @@
{
"semi": false,
"singleQuote": true
}
21 changes: 13 additions & 8 deletions index.js
Expand Up @@ -2,16 +2,16 @@ 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
module.exports = function svgLoader(options = {}) {
const { svgoConfig, svgo, defaultImport, componentParamAlias } = options

const svgRegex = /\.svg(\?(raw|component|skipsvgo))?$/

return {
name: 'svg-loader',
enforce: 'pre',

async load (id) {
async load(id) {
if (!id.match(svgRegex)) {
return
}
Expand All @@ -29,7 +29,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 +43,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, `<${componentParamAlias || 'component'} is="style"`)
.replace(/<\/style/g, `</${componentParamAlias || '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 5191860

Please sign in to comment.