跳到主要内容

vite-plugin-svgr

2023年12月20日
柏拉文
越努力,越幸运

一、认识


vite-plugin-svgr 用于以组件的形式加载 SVG。主要逻辑在 transform 钩子中完成,流程如下:

  1. 根据 id 入参过滤出 svg 资源

  2. 读取 svg 文件内容

  3. 利用 @svgr/coresvg 转换为 React 组件代码

  4. 将组件的 jsx 代码转译为浏览器可运行的代码。

二、实现


import * as fs from 'fs';
import { Plugin, transformWithEsbuild } from 'vite';

export default function vitePluginSvgr(): Plugin {

return {
name: 'vite-plugin-svgr',
async transform(code, id) {

if (!id.endsWith('.svg')) {
return code;
}

const { transform } = await import("@svgr/core");
const { default: jsx } = await import("@svgr/plugin-jsx");

const filePath = String(id);
const svgCode = await fs.promises.readFile(filePath, "utf8");

const componentCode = await transform(svgCode, {}, {
filePath,
caller: {
defaultPlugins: [jsx],
},
});

const result = await transformWithEsbuild(componentCode, id, {
loader: 'jsx',
});

return {
map: null,
code: result.code,
};
}
};
}

三、配置


// vite.config.ts
import svgr from './plugins/svgr';

// 返回的配置
{
plugins: [
// 省略其它插件
svgr()
]
}

四、测试


在项目中用组件的方式引入 svg:

import ReactLogo from "./assets/react.svg"

function App() {
return <div className="">
<ReactLogo />
</div>;
}

export default App;