jfgodoy/vite-plugin-solid-svg · 文件 下载 ZIP
文件最后提交记录最后更新时间
README.md
以下内容由 AI 翻译,如有问题请点此提交 issue 反馈
vite-plugin-solid-svg
扩展 Vite,使其能够使用 SVG 文件作为 Solid.js 组件。
功能:
- SVGO 优化
- 热模块替换支持
- 支持
?component-solid查询字符串 - SSR
当前支持的 Vite 版本:
4 or above
安装
yarn add --dev vite-plugin-solid-svg
pnpm i -D vite-plugin-solid-svg
设置
// vite.config.js
import solidPlugin from 'vite-plugin-solid'
import solidSvg from 'vite-plugin-solid-svg'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [solidPlugin(), solidSvg()],
})
typescript
vite 为其自身的 "*.svg" 添加了定义,并将它们定义为 string。据我所知,这无法被覆盖。
因此,我们有两个选择:将我们的类型放在 vite 的类型之前,或者使用带有查询字符串的导入。
如果你使用的是默认的 defaultAsComponent,你需要在 tsconfig 中将我们的类型定义放在 vite 之前。
// tsconfig.json
"compilerOptions": {
"types": [
"vite-plugin-solid-svg/types-component-solid"
"vite/client",
],
},
如果你更改为 defaultAsComponent=false,你应该使用一个不同的类型定义,该定义仅在匹配查询字符串时将 svg 导入识别为 solid 组件。在这种情况下,将其放在 "vite/client" 之前
// tsconfig.json
"compilerOptions": {
"types": [
"vite-plugin-solid-svg/types",
"vite/client"
],
},
import MyIcon from './my-icon.svg'; // <-- this will match vite module definition, and therefore identified as string
import MyIcon from './my-icon.svg?component-solid'; // <-- this will match the definition in this plugin, and therefore identified as Solid Component
选项
SolidSvg({
/**
* If true, will export as JSX component if `as` isn't specified.
*
* Otherwise will export as url, or as JSX component if '?as=component-solid'
*
*/
defaultAsComponent: true,
svgo: {
enabled: true, // optional, by default is true
svgoConfig: <svgo config> // optional, if defined, the file svgo.config.js is not loaded.
}
})
如果需要配置 svgo,你也可以在项目的根目录中创建一个配置文件 svgo.config.js,具体说明请参阅 svgo 文档。svgo.svgoConfig 的优先级高于该文件。
用法
作为 Solid.js 组件导入:
import MyIcon from './my-icon.svg?component-solid';
// or './my-icon.svg' if `defaultAsComponent` is `true`
import MyIcon from './my-icon.svg';
const App = () => {
return (
<div>
<h1> Title </h1>
<MyIcon />
</div>
);
};
export default App;
要导入文件夹内的所有 svg,请使用 import.meta.glob('@/svgs/*.svg', { as: 'component-solid' })。有关更多详细信息,请参阅 Vite 文档。
const icons = import.meta.glob('./*.svg', { as: 'component-solid' })
/*
icons = {
icon1: () => import("./icon1.svg"),
icon2: () => import("./icon2.svg")
}
*/
const App = () => {
const Icon1 = lazy(() => iconsDic.icon1())
return (
<div>
<p>hello</p><Icon1 />
</div>
);
};
export default App;
原因
在 Solidjs + vite 项目中,你可以轻松使用以下方式添加 svg 图像:
import iconUrl from './icon.svg'
const App = () => {
return (
<div>
<img href={iconUrl}>
</div>
)
}
然而,图像的填充颜色无法被覆盖。将 svg 作为组件导入可以解决此问题,并允许 css 样式级联到 svg 内容中。此外,可能存在需要确保图像已完全加载的情况,例如,在开始动画之前。此模块提供了一个组件,您可以控制其加载时机。
Credits
This plugin is based on the work from the following projects: