在SvelteKit中如何读取静态SVG文件内容为字符串?
解决方案
SvelteKit 基于 Vite 构建,有两种成熟方案可以直接拿到 SVG 文本内容,实现用 CSS 控制图标颜色的需求。
方法1:使用 Vite 的?raw后缀静态导入SVG(推荐)
直接给 SVG 导入路径加?raw后缀,就能在编译阶段直接拿到 SVG 的纯文本内容,没有运行时开销,代码最整洁。
修改后的示例代码如下:
<script lang="ts"> export let currentRoute: string; // 导入SVG内容,$lib是SvelteKit内置别名,对应src/lib目录 import homeIcon from '$lib/icons/home.svg?raw'; import serversIcon from '$lib/icons/servers.svg?raw'; type Route = { icon: string; name: string; path: string }; const routes: Route[] = [ { icon: homeIcon, name: 'Home', path: '/' }, { icon: serversIcon, name: 'Servers', path: '/servers' } ]; </script> <nav> <ul> {#each routes as route} <li class:active={currentRoute === route.path}> <a href={route.path}> <!-- 用@html指令渲染SVG内容 --> <span class="icon">{@html route.icon}</span> <p>{route.name}</p> </a> </li> {/each} </ul> </nav> <style> .active { color: #2563eb; /* 自定义激活状态的文本和图标颜色 */ } /* 让SVG继承父元素的颜色配置 */ .icon :global(svg) { fill: currentColor; width: 1em; height: 1em; } </style>
注意:提前把 SVG 文件内写死的
fill属性删除,或者改为fill="currentColor",才能正常继承父元素的颜色。
方法2:运行时动态fetch读取SVG
如果你的图标路径是动态生成的、无法提前静态导入,可以用fetch在运行时读取public目录下的SVG内容:
// 封装读取SVG的工具函数 async function loadSvgContent(path: string): Promise<string> { const res = await fetch(path); return res.text(); }
如果SVG存放在public目录下,路径直接写绝对路径即可,比如/icons/servers.svg。该方案适合图标列表不固定的场景,需要额外处理加载状态避免界面闪烁。
内容的提问来源于stack exchange,提问作者tzimom
相关产品推荐
相关产品推荐

