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

使用Trunk打包CSS配合Yew时,生成的index.html缺失CSS链接

问题:Trunk构建Yew项目时未自动注入哈希后的CSS链接到index.html

我在Yew项目中尝试用Trunk打包CSS文件,已按文档完成配置。Trunk构建后会把哈希处理后的CSS文件放到指定目录,但生成的index.html里却没有添加指向该哈希文件名的link标签。

最小复现示例

文件结构

项目根目录包含:

  • Trunk.toml
  • index.html
  • src/
    • main.rs
    • static_html/
      • styles.css

Trunk.toml

[build]
dist = "/usr/share/nginx/html"
public_url = "/"
release = false

index.html

<!doctype html>
<html lang="en">
<head>
    <h2>Loading...</h1>
    <link data-trunk rel="css" href="src/static_html/styles.css" />
    <meta charset="utf-8">
</head>
<body>
    <h3>This should display while loading</h3>
</body>
</html>

main.rs

use yew::{html, Html};
use yew::function_component;

fn main() {
    yew::Renderer::<Main>::new().render();
}

#[function_component]
fn Main() -> Html {
    html! {
        <div>
            {"I expect large green text on a red background"}
        </div>
    }
}

styles.css

body { 
    background-color: red; 
    font-size: 5em;
    color: green;
}

现象与预期

  • 构建后哈希后的CSS文件已出现在指定的dist目录中,但生成的index.html里没有对应的link标签,页面无样式。
  • 手动给index.html添加指向哈希后CSS文件的link标签,样式可正常生效。期望Trunk构建时自动将哈希文件名注入到HTML中。

解决方法

  1. 修复HTML标签错误
    你的index.html存在标签不匹配问题:<h2>Loading...</h1>,需改为<h2>Loading...</h2>。Trunk处理HTML时若遇到格式错误,可能会中断资源注入流程。

  2. 更新Trunk到最新版本
    旧版本Trunk可能存在资源注入Bug,执行命令更新:

    cargo install trunk --force
    
  3. 清理构建缓存后重新构建
    缓存异常可能导致资源注入失败,执行以下命令:

    trunk clean
    trunk build
    
  4. 检查路径正确性
    确认src/static_html/styles.css的相对路径无误,Trunk需准确定位到该文件才能完成处理和注入。

  5. 查看详细构建日志
    执行带日志参数的构建命令,排查是否有CSS处理相关的错误提示:

    trunk build -v
    

内容的提问来源于stack exchange,提问作者Daniel McMath

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:34:57