步骤:
cargo generate --git https://github.com/rustwasm/wasm-pack-template
项目名称: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
包含所有必要的详细信息:
[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"
在项目目录中执行命令:
# 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);
最后,在项目根目录中:
deno run --allow-read deno/main.ts
但是出现以下错误:
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
这就是我要执行的操作:我想从rust文件生成.wasm
文件(使用wasm-pack
),将该文件导入.ts
文件中,然后执行{{1 }}。但是我无法解决最后一步。
我尝试使用wasi,但没有用。
在rustwasm guide的帮助下,按照上述步骤操作,并使用deno
/ node
代替js
/ deno
可以很好地工作。
但是
如何使用ts
+ deno
实现我上面提到的目标?
答案 0 :(得分:0)
构造函数需要imports
对象:
const imports = { };
const wasmInstance = new WebAssembly.Instance(wasmModule, imports);