109149
109149

Reputation: 1562

How to import wasm file generated by wasm-pack inside typescript file?

Steps:

cargo generate --git https://github.com/rustwasm/wasm-pack-template

Project name: project-name

// src/lib.rsj
mod utils;

use wasm_bindgen::prelude::*;

#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

#[wasm_bindgen]
struct Temp;

#[wasm_bindgen]
impl Temp {
    pub fn hello() -> String {
        String::from("QWE")
    }
}

Cargo.toml has all necessary details:

[lib]
crate-type = ["cdylib", "rlib"]

[features]
default = ["console_error_panic_hook"]

[dependencies]
wasm-bindgen = "0.2.63"

console_error_panic_hook = { version = "0.1.6", optional = true }

wee_alloc = { version = "0.4.5", optional = true }

[dev-dependencies]
wasm-bindgen-test = "0.3.13"

[profile.release]
opt-level = "s"

In project directory execute commands:

# builds and makes pkg directory in root directory with .js .ts and .wasm files
wasm-pack build

mkdir deno
touch deno/main.ts
// deno/main.ts

const filename = "<absolute-path>/pkg/project_name_bg.wasm";
const wasmCode = await Deno.readFile(filename);
const wasmModule = new WebAssembly.Module(wasmCode);
const wasmInstance = new WebAssembly.Instance(wasmModule);
const {
    Temp,
} = wasmInstance.exports;

console.log(Temp);

And finally, in project root directory:

deno run --allow-read deno/main.ts

But I get the following error:

error: Uncaught TypeError: WebAssembly.Instance(): Imports argument must be present and must be 
an object
const wasmInstance = new WebAssembly.Instance(wasmModule);
                     ^
    at file:///.../project-name/deno/main.ts:5:22

Here's what I am trying to do: I would like to generate .wasm file from rust files (using wasm-pack), import that file inside .ts file and execute with deno. But I can't fix the last step.

I tried using wasi, didn't work. Going through the steps above and using node/js instead deno/ts works fine with the help of the rustwasm guide.

But

How can I achieve what I mentioned above using deno + ts?

Upvotes: 3

Views: 1747

Answers (1)

Chakrit W
Chakrit W

Reputation: 392

The constructor requires imports object:

const imports = { };
const wasmInstance = new WebAssembly.Instance(wasmModule, imports);

Upvotes: 0

Related Questions