Here are the steps you need to follow:
cargo generate --git https://github.com/rustwasm/wasm-pack-template
Specify your project name as: 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
contains all the 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 your project directory, run the following commands:
# Build and create a pkg directory in the root 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);
Finally, in your project's root directory, execute:
deno run --allow-read deno/main.ts
However, if you encounter the following error:
Error: Uncaught TypeError: WebAssembly.Instance(): The 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
Your goal is to generate a .wasm file from Rust files using wasm-pack, import that file into a .ts file, and execute it using Deno. You may have tried using wasi without success. Following similar steps with node/js instead of deno/ts worked fine according to the rustwasm guide.
However,
How can you accomplish this task using Deno + TS?