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

能否从单个Yew项目生成多份含关联JS/WASM的HTML静态文件?

从单个Yew项目生成多份独立HTML输出

可以实现,但直接创建多个Renderer实例无法生成独立的多份HTML产物,需要通过拆分入口、调整构建配置来完成,具体步骤如下:

1. 定义多个根组件

在项目中创建多个独立的根组件,作为不同页面的入口:

// src/lib.rs
use yew::prelude::*;

#[function_component(App1)]
pub fn app1() -> Html {
    html! { <h1>{"页面1内容"}</h1> }
}

#[function_component(App2)]
pub fn app2() -> Html {
    html! { <h1>{"页面2内容"}</h1> }
}

2. 创建多个二进制入口文件

为每个根组件单独创建入口文件,放在src/bin目录下:

  • src/bin/app1.rs:
use yew::Renderer;
use your_crate_name::App1;

fn main() {
    Renderer::<App1>::new().render();
}
  • src/bin/app2.rs:
use yew::Renderer;
use your_crate_name::App2;

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

3. 配置Trunk构建多产物

如果使用Trunk作为构建工具,需为每个页面创建独立的HTML模板,并指定输出目录:

  • 项目根目录创建app1.html:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>页面1</title>
</head>
<body>
    <script type="module">
        import init from './app1.js';
        init();
    </script>
</body>
</html>
  • 同理创建app2.html,将脚本路径改为./app2.js。

执行以下命令分别构建:

trunk build --index app1.html --output dist/app1
trunk build --index app2.html --output dist/app2

完成后dist目录下会生成app1和app2两个子目录,每个目录都包含独立的HTML、JS和WASM文件,模块路径均为相对路径。

4. 关键注意事项

  • 通用组件逻辑可放在src/lib.rs中,供所有入口复用
  • 若使用Webpack等其他构建工具,需配置多入口打包规则,绑定对应的HTML模板
  • 确保构建工具自动处理WASM模块的相对路径映射,避免加载错误

内容的提问来源于stack exchange,提问作者Mattia Samiolo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:45:48