你不能import 但如果你得到.wasm 文件的字节格式,你可以在任何javascript 文件中使用它。我将展示您可以处理的 2 种方法:
-
将 wasm 文件放在 public 文件夹中并获取它:
异步函数 getByte() {
try {
const res = await fetch("test.wasm");
// bytes from memory
const buffer = await res.arrayBuffer();
// this will create an object
const wasm = await WebAssembly.instantiate(buffer);
console.log(wasm);
// addTwo function is exported in wasm code, otherwise I would not be able to use it.
const addNumbers = wasm.instance.exports.addTwo;
// console.log(addNumbers);
const result = addNumbers(10, 50);
console.log(result);
} catch (e) {
console.log(e);
}
}
-
在 linux 中,xxd 命令创建给定文件或标准输入的十六进制转储。例如 xxd -g1 test.wasm 将创建 wasm 的十六进制格式。
现在您可以像这样在 javascript 文件中使用它们:
async function byteCode() {
const byteArray = new Int8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01,
0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07,
0x07, 0x01, 0x03, 0x73, 0x75, 0x6d, 0x00, 0x00, 0x0a, 0x09, 0x01,
0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b, 0x00, 0x18, 0x04,
0x6e, 0x61, 0x6d, 0x65, 0x01, 0x06, 0x01, 0x00, 0x03, 0x73, 0x75,
0x6d, 0x02, 0x09, 0x01, 0x00, 0x02, 0x00, 0x01, 0x61, 0x01, 0x01,
0x62,
]);
// WebAssembly is globally available
// this will create a javascript object
const wasm = await WebAssembly.instantiate(byteArray.buffer);
// you need to know methods in original code
// in test.wasm I wrote a function and exported as "sum"
const addNumbers = wasm.instance.exports.sum;
const result = addNumbers(10, 50);
console.log(result);
}