Preact+Vite项目中SVG作为组件导入的问题求助
解决方案一:修复vite-plugin-svgr的TS错误并正确导入SVG组件
添加TypeScript类型声明
在项目src目录下创建svg.d.ts文件,写入以下类型声明:declare module '*.svg?component' { import type { Component, JSX } from 'preact'; const SVGComponent: Component<JSX.SVGAttributes<SVGSVGElement>>; export default SVGComponent; }确保该文件被
tsconfig.json的include字段覆盖:{ "include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.tsx"] }验证vite-plugin-svgr配置
确认vite.config.js中插件顺序和参数正确(svgr需放在preact插件之前,保证SVG优先被转换):import { defineConfig } from 'vite'; import preact from '@preact/preset-vite'; import svgr from 'vite-plugin-svgr'; import tsconfigPaths from 'vite-tsconfig-paths'; export default defineConfig({ plugins: [ svgr({ svgrOptions: { jsxRuntime: 'classic-preact', dimensions: false // 移除SVG默认宽高,让Tailwind样式控制尺寸 } }), preact(), tsconfigPaths() ] });导入并使用SVG组件
现在可以正常导入并传递Tailwind类名或SVG属性:import Search from 'assets/icons/search-lg.svg?component'; function SearchButton() { return ( <button className="p-2 hover:bg-gray-100"> <Search className="w-5 h-5 text-gray-700" /> </button> ); }
解决方案二:创建可定制的Preact SVG组件
如果不想依赖SVGR插件,可直接封装内联SVG组件,完全掌控元素和样式:
基础内联SVG组件模板
将SVG代码写入Preact组件,通过props接收样式和自定义参数:import type { JSX } from 'preact'; interface SearchIconProps extends JSX.SVGAttributes<SVGSVGElement> { isHighlighted?: boolean; } export function SearchIcon({ className, isHighlighted = false, ...props }: SearchIconProps) { const fillClass = isHighlighted ? 'text-blue-500' : 'text-gray-700'; return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" className={`w-5 h-5 ${className} ${fillClass}`} {...props} > <path d="M11.5 21c-5.071 0-9.25-4.179-9.25-9.25S6.429 2.5 11.5 2.5 20.75 6.679 20.75 11.75 16.571 21 11.5 21Zm0-16.5c-4.017 0-7.25 3.233-7.25 7.25s3.233 7.25 7.25 7.25 7.25-3.233 7.25-7.25-3.233-7.25-7.25-7.25Z" /> <path d="M21.707 20.293 16.314 14.9a1.001 1.001 0 0 0-1.414 1.414l5.393 5.393a.997.997 0 0 0 1.414 0 .999.999 0 0 0 0-1.414Z" /> </svg> ); }批量处理仓库中的SVG
若SVG存于单独仓库,可通过SVGR CLI批量转换为Preact组件:npx @svgr/cli --jsx-runtime classic-preact --out-dir src/components/icons/ path/to/your/svg/repo/转换后可批量修改生成的组件,添加
className等props支持,实现Tailwind样式定制。
内容的提问来源于stack exchange,提问作者fhueser
相关产品推荐
相关产品推荐

