Created
March 24, 2022 18:01
-
-
Save meyt/925788c116cb6d8227f0eaa8fc2ee7f5 to your computer and use it in GitHub Desktop.
Import SVG as Vue2 component for Vite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// npm i --save-dev vue-template-compiler@2.6.14 vue-template-es2015-compiler@1.9.1 svgo@2.8.0 | |
const fs = require('fs') | |
const svgo = require('svgo') | |
const transpile = require('vue-template-es2015-compiler') | |
const compiler = require('vue-template-compiler') | |
async function compileSvg (source, id) { | |
source = compiler.compile(source, { preserveWhitespace: false }).render | |
source = `module.exports = { render: function () { ${source} } };` | |
return transpile(source).replace('module.exports =', 'export default') | |
} | |
async function optimizeSvg (content, path) { | |
const { data } = await svgo.optimize(content, { path }) | |
return data | |
} | |
export default function (options) { | |
const cache = new Map() | |
const svgRegex = /\.svg$/ | |
return { | |
name: 'vue-svg', | |
async transform (source, id, isBuild) { | |
let result = id.match(svgRegex) | |
if (result) { | |
result = cache.get(id) | |
if (!result) { | |
result = fs.readFileSync(id) | |
result = await optimizeSvg(result, id) | |
result = await compileSvg(result, id) | |
if (isBuild) cache.set(id, result) | |
} | |
return result | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment