官方示例地址
node 版本16.14.2
建立一个新项目
初始化
npm init
安装 AssemblyScript 编译器。
npm install --save-dev assemblyscript
安装后,编译器提供了一个方便的脚手架实用程序来快速设置一个新项目,在当前目录中
npx asinit .
该asinit命令会自动创建推荐的目录结构和配置文件:
./assembly
存放编译为WebAssembly的AssemblyScript源的目录
./assembly/tsconfig.json
TypeScript configuration inheriting recommended AssemblyScript settings.
./assembly/index.ts
TypeScript配置继承了推荐的AssemblyScript设置。
./build
Build artifact directory where compiled WebAssembly files are stored.
./build/.gitignore
构建工件目录,其中存储已编译的WebAssembly文件。
./asconfig.json
Configuration file defining both a ‘debug’ and a ‘release’ target.
./package.json
定义了“调试”和“发布”目标的配置文件。
./tests/index.js
状态测试,检查模块是否正常工作。
./index.html
在浏览器中加载模块的初始HTML文件
assembly/index.ts现在可以通过调用 build 命令将示例中的示例编译为 WebAssembly
npm run asbuild
构建后,该目录包含使用该模块的所有位,就像任何其他现代 Node.js ESM 模块一样
生成的index.html显示了如何在 Web 上使用该模块。为模块目录提供服务的 Web 服务器,默认为 display index.html,可以通过以下方式启动:
npm start
端口默认启动3000
这时候就已经可以打开看到一个小demo了
但是根据官方示例。想改为示例中的样子
根据示例提示。 先将示例中的module.ts复制到assembly/index.ts下
package.json 文件中 “asbuild:release”: “asc assembly/index.ts --target release” 改为 “asbuild:release”: "asc assembly/index.ts --target release --runtime stub --use Math=JSMath --importMemory "
执行 npm run asbuild
将官网给的示例代码复制到根目录下的index.html文件
在script标签中 将 对应代码注释掉
然后将下列代码复制到刚刚注释掉的代码下方
async function instantiate(module, imports = {}) {
const adaptedImports = {
env: Object.assign(Object.create(globalThis), imports.env || {}, {
"Math.log": (
// ~lib/bindings/dom/Math.log(f64) => f64
Math.log
),
"Math.log2": (
// ~lib/bindings/dom/Math.log2(f64) => f64
Math.log2
),
}),
};
const {
exports
} = await WebAssembly.instantiate(module, adaptedImports);
return exports;
}
const exports =await (async url => instantiate(
await (async () => {
try {
return await globalThis.WebAssembly.compileStreaming(globalThis.fetch(url));
} catch {
return globalThis.WebAssembly.compile(await (await import("node:fs/promises")).readFile(url));
}
})(), { env: {
memory
}}))(new URL("/build/release.wasm",location.href))
保存 。
执行 npm start
打开 对应端口