我正在尝试使用 Assemblyscript 将 TypeScript 编译为 WebAssembly,并且尝试从 WebAssembly 导出一个类,以便可以在 JavaScript 中使用它。为了澄清,我希望能够在 .js 文件中构造该类的新实例,即使该类是在 .wasm 中定义的。
我做了一些研究和实验,似乎 Assemblyscript 会将类方法导出为函数,而不是将类作为一个整体导出。
这就是我希望它在 WebAssembly 端的外观:
export class Point {
public x: i32;
public y: i32;
constructor(x: i32, y: i32) {
this.x = x;
this.y = y;
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我想在 JavaScript 方面完成的任务:
// Omitted code for instatiating the Wasm Module
var exports = object.instance.exports; // The exports of the Wasm instance
var Point = exports.Point; // The Point class
let point = new Point(0, 0) // …Run Code Online (Sandbox Code Playgroud) 我有一个用 TypeScript 编写的现有项目,我正在尝试导入 WebAssembly 模块来替换某些功能。
我通过提取将 .wasm 加载到 .js 文件的逻辑,成功导入了 WebAssembly 模块。这是它自己的 TypeScript 模块,并导入到我想要使用 WebAssembly 函数的 .ts 文件中。
为了演示目的,我在 wasm 中做了一个简单的添加函数。
在使用 AssemblyScript 编译为 .wasm 的 .ts 中:
export function add(a: i32, b: i32): i32 {
return a + b;
}
Run Code Online (Sandbox Code Playgroud)
在 .js 文件中:
export async function loadWasm() {
const imports = {}; // Omitted the contents since it's most likely irrelevant
const module = await
WebAssembly.instantiateStreaming(fetch('path/to/file.wasm'),imports);
return module;
}
Run Code Online (Sandbox Code Playgroud)
在我想使用 WebAssembly 的 .ts 文件中:
export async function loadWasm() { …Run Code Online (Sandbox Code Playgroud)