#html #js #self-contained #compile #wasm-bindgen #cargo #profile

bin+lib wasm-bundle

使用 WASM 将 Rust 代码编译成自包含的 .js.html 文件

3 个版本 (重大更新)

0.3.0 2023 年 6 月 26 日
0.2.0 2023 年 4 月 2 日
0.1.0 2023 年 3 月 31 日

Cargo 插件 中排名 693

每月下载次数 21

Apache-2.0 或 MIT

13KB
262

cargo-wasm-bundle

使用 WASM 将 Rust 代码编译成自包含的 .js.html 文件。

安装

cargo install wasm-bundle

这将在您的 cargo 二进制目录(通常为 ~/.cargo/bin)中提供 cargo-wasm-bundle 二进制文件。要将其用作 cargo 扩展(cargo wasm-bundle),则 cargo-wasm-bundle 必须存在于 $PATH 中的任何目录中。

用法

CLI 的模式基于 cargo build,但目前仅支持有限数量的 crate 布局和选项。如果这不足以满足您的需求,请提交一个 issue。

构建默认的二进制目标(src/main.rs)。

cargo wasm-bundle

生成的 .html.js 文件位于 target/wasm-bundle/<profile>/。要运行程序,请在浏览器中打开 .html 文件。

示例目标

二进制目标(/example/demo.rs

cargo wasm-bundle --example demo

发布配置文件

您可以在任何 cargo wasm-bundle 命令中添加 --release 标志来启用发布配置文件。

cargo wasm-bundle --release

JavaScript 模块

除了 .html 文件外,还会生成一个自包含的 .js 模块。通过调用默认导出来运行 WASM 程序。

<html>
<body>
    <script type="module">
        import init from "./my_crate.js";
        init();
    </script>
</body>
</html>

wasm-bindgen

这个 crate 使用了 wasm-bindgen-cli。wasm-bindgen-cli 和 wasm-bindgen 依赖项版本不匹配可能导致编译错误。最简单的解决方案是将两者都更新到最新版本

cargo update -p wasm-bindgen
cargo install -f wasm-bindgen-cli

什么可行,什么不可行

本 crate 的 examples 目录包含可运行的 crate。在 wasm-bundle 的 crate 根目录下运行 cargo test 命令,为所有示例 crate 创建相应的 .html 文件(examples/<example>/index.html)。

什么可行

  • 默认二进制目标(src/main.rs
  • 示例二进制目标(examples/demo.rs

未测试/不可行

  • 库目标
  • 额外的二进制目标
  • 自定义二进制目标未经测试

如果您需要额外的功能,请考虑在 GitHub 上提交问题,也许可以贡献一个匹配的示例 crate 布局。

开发

要使用 cargo wasm-bundle 命令测试本地更改

  1. 克隆仓库
  2. 进行更改并构建
  3. 在测试 crate 根目录下运行 PATH=<wasm_bundle>/target/debug/:$PATH cargo wasm-bundle

许可证

根据您选择以下任一项进行许可

任选其一。

贡献

除非您明确表示,否则根据 Apache-2.0 许可证定义的,您有意提交的任何贡献,均应按照上述方式进行双许可,不附加任何额外条款或条件。

依赖项

~3–4.5MB
~110K SLoC