You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:27:03