Front End

[FE] hello assemblyscript

2018-07-10  本文已影响2人  何幻

1. 背景

AssemblyScript 是一个从 TypeScriptWebAssembly 的编译器。

2. 环境初始化

2.1 新建工程

$ mkdir test-assemblyscript && cd test-assemblyscript && npm init -f

2.2 安装依赖

$ npm i -S AssemblyScript/assemblyscript glob

目录结构

.
├── node_modules
├── package-lock.json
└── package.json

3. assemblyscript相关

3.1 生成脚手架

$ npx asinit .

目录结构

.
├── assembly
│   ├── index.ts
│   └── tsconfig.json
├── build
│   └── .gitignore
├── index.js
├── node_modules
│   ├── .bin
│   │   ├── asc
│   │   ├── asinit
│   │   ├── binaryen-as
│   │   ├── binaryen-dis
│   │   └── binaryen-opt
├── package-lock.json
└── package.json

注:
(1)npx是npm默认全局安装的一个包,即,

$ npm install -g npx

npx用于执行包中的二进制文件,
npx asinit .,相当于`npm bin`/asinit .,即./node_modules/.bin/asinit .

Executes <command> either from a local node_modules/.bin, or from a central cache, installing any packages needed in order for <command> to run.

(2)index.js内容如下,

const fs = require("fs");
const compiled = new WebAssembly.Module(fs.readFileSync(__dirname + "/build/optimized.wasm"));
const imports = {};
Object.defineProperty(module, "exports", {
  get: () => new WebAssembly.Instance(compiled, imports).exports
});

其中,new WebAssembly.Module用来加载wasm模块。

Object.defineProperty(module, "exports", { get: ()=> ... });
用来给module定义一个名为exportget方法,
参考,Object.defineProperty

3.2 构建

$ npm run asbuild

4. 例子

新建main.js

const { add } = require('./index');

const r = add(1, 2);
console.log(r);

node运行一下,

$ node main.js
> 3

参考

github: AssemblyScript/assemblyscript
npx
Object.defineProperty

上一篇 下一篇

猜你喜欢

热点阅读