Alejandro BG
Alejandro BG

Reputation: 61

How to include webassembly with typescript (without nodejs)

I would like to know if there is any way, as simple as possible, to include webassembly with typescript, I don't use node. If I activate the option allowJs: true in tsconfig.json and I manually move the wasm file it works. This solution does not seem very clean, because I have two "glue" files (network_calculator_lib.js) quite similar. Even so I tested if it could be compiled in the same folder and as I could imagine it cannot, it does not allow to overwrite the file.

I hope I have explained me good enough. I am using Rust to compile a Webassembly with wasm-pack, although I would prefer to be able to directly import the wasm. As a webserver I am also using one written in Rust using actix web.

Apologies and thanks in advance if I ask something very silly, but most use webpack / node and I have not found any information that clarifies me.

Project tree

Upvotes: 1

Views: 3106

Answers (1)

Alejandro BG
Alejandro BG

Reputation: 61

This code resolve my problem:

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()

For people who are having similar problems:

  • Compile rust with web target option: wasm-pack build --target web.
  • In HTML, JS file or code need to be module type: <script type="module" src="./scripts/js/index.js"></script>.
  • In Cargo.toml:
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
  • Package.json is not really needed.

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

Upvotes: 3

Related Questions