WebAssembly.compile()

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since October 2017.

* Some parts of this feature may have varying levels of support.

WebAssembly.compile() 静态方法将 WebAssembly 二进制代码编译为一个 WebAssembly.Module 对象。如果在实例化模块之前必须要对其进行编译,那么这个函数很有帮助(否则,应该使用 WebAssembly.instantiate() 函数)。

备注: 有严格内容安全策略(CSP)的网页可能会阻止 WebAssembly 编译和执行模块。与允许 WebAssembly 编译和执行有关的额外信息,参见 script-src CSP

语法

js
WebAssembly.compile(bufferSource)
WebAssembly.compile(bufferSource, compileOptions)

参数

bufferSource

一个类型化数组ArrayBuffer,包含你想编译的 Wasm 模块的二进制代码。

compileOptions 可选

一个编译选项的对象。属性包括:

builtins 可选

一个由一个或多个字符串组成的数组,用于在编译的 Wasm 模块中启用 JavaScript 内置功能。字符串定义你想启用的内置功能。当前,唯一可用的值是 "js-string",启用的是 JavaScript 字符串内置功能。

importedStringConstants 可选

一个字符串,为导入的全局字符串常量指定命名空间。如果你希望在 Wasm 模块中使用导入的全局字符串常量,就需要指定这个属性。

返回值

一个 Promise,兑现为表示已编译模块的 WebAssembly.Module 对象。

异常

示例

使用编译

下面的例子使用 compile() 函数编译加载的 simple.wasm 字节码,然后使用 postMessage() 将其发送给一个 worker

js
const worker = new Worker("wasm_worker.js");

fetch("simple.wasm")
  .then((response) => response.arrayBuffer())
  .then((bytes) => WebAssembly.compile(bytes))
  .then((mod) => worker.postMessage(mod));

备注: 在多数情况下,你可能想要使用 WebAssembly.compileStreaming(),因为它比 compile() 效率更高。

启用 JavaScript 内置功能和全局字符串导入

这个例子在用 compile() 编译 Wasm 模块时,启用 JavaScript 字符串内置功能和导入的全局字符串常量,然后用 instantiate() 将其实例化,接着运行导出的 main() 函数(其向控制台打印 "hello world!")。查看其在线版本

js
const importObject = {
  // 常规导入
  m: {
    log: console.log,
  },
};

const compileOptions = {
  builtins: ["js-string"], // 启用 JavaScript 字符串内置功能
  importedStringConstants: "string_constants", // 启用导入的全局字符串常量
};

fetch("log-concat.wasm")
  .then((response) => response.arrayBuffer())
  .then((bytes) => WebAssembly.compile(bytes, compileOptions))
  .then((module) => WebAssembly.instantiate(module, importObject))
  .then((instance) => instance.exports.main());

规范

Specification
WebAssembly JavaScript Interface
# dom-webassembly-compile

浏览器兼容性

参见