如何使用 typescript 包含 webassembly(没有 nodejs)

How to include webassembly with typescript (without nodejs)

我想知道是否有任何方法,尽可能简单,将 webassembly 包含在打字稿中,我不使用节点。 如果我在 tsconfig.json 中激活选项 allowJs: true 并手动移动 wasm 文件,它就会工作。 这个解决方案看起来不是很干净,因为我有两个非常相似的“胶水”文件(network_calculator_lib.js)。尽管如此,我还是测试了它是否可以在同一个文件夹中编译,正如我想象的那样,它不允许覆盖文件。

我希望我已经解释得足够好。 我正在使用 Rust 编译带有 wasm-pack 的 Webassembly,尽管我更希望能够直接导入 wasm。 作为网络服务器,我还使用了一个使用 actix web 用 Rust 编写的网络服务器。

如果我问的问题很愚蠢,我深表歉意并提前致谢,但大多数人都使用 webpack / node,我还没有找到任何可以澄清我的信息。

这段代码解决了我的问题:

import init, { exported_wasm_func } from '../pkg/network_calculator_lib.js';
async function run() {
    await init(); // You need to call init before wasm functions.
    document.body.textContent = exported_wasm_func();
}
run()

对于遇到类似问题的人:

  • 使用 web 目标选项编译 rust:wasm-pack build --target web.
  • 在HTML中,JS文件或代码需要是模块类型:<script type="module" src="./scripts/js/index.js"></script>.
  • 在Cargo.toml中:
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
  • Package.json并不是真的需要。

来源:https://aralroca.com/blog/first-steps-webassembly-rust