-
-
Save phaistonian/e96e2f1363b42b1ede470a974fd006bc to your computer and use it in GitHub Desktop.
svg-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
import fs from 'fs'; | |
import { transform as convert } from '@svgr/core'; | |
import { optimize as optimizeSvg } from 'svgo'; | |
import { transformWithEsbuild } from 'vite'; | |
export default (options = {}) => { | |
const { svgrOptions = {}, esbuildOptions = {}, svgo = false, svgoConfig = {} } = options; | |
return { | |
name: 'vite:svgr', | |
enforce: 'pre', | |
async transform(_, id) { | |
if (!id.endsWith('.svg')) { | |
return undefined; | |
} | |
const [, query] = id.split('?', 2); | |
// Return as url | |
if (query === 'url') { | |
return id; | |
} | |
let svgCode = await fs.promises.readFile(id, 'utf8'); | |
if (svgo) { | |
svgCode = optimizeSvg(svgCode, svgoConfig).data; | |
} | |
if (query === 'raw') { | |
return svgCode; | |
} | |
const componentCode = await convert( | |
svgCode, | |
{ | |
...svgrOptions, | |
plugins: ['@svgr/plugin-jsx'], | |
}, | |
{ | |
componentName: 'ReactComponent', | |
} | |
).then(res => res); | |
const res = await transformWithEsbuild(componentCode, id, { loader: 'jsx', ...esbuildOptions }); | |
return { | |
code: res.code, | |
map: null, | |
}; | |
}, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment