Skip to content

Instantly share code, notes, and snippets.

@phaistonian
Created November 14, 2024 10:26
Show Gist options
  • Save phaistonian/e96e2f1363b42b1ede470a974fd006bc to your computer and use it in GitHub Desktop.
Save phaistonian/e96e2f1363b42b1ede470a974fd006bc to your computer and use it in GitHub Desktop.
svg-vite
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