WebAssembly.compile()
Baseline 广泛可用 *
WebAssembly.compile()
静态方法将 WebAssembly 二进制代码编译成一个 WebAssembly.Module
对象。如果需要在实例化之前编译模块,此函数非常有用(否则,应使用 WebAssembly.instantiate()
函数)。
注意: 具有严格 Content Security Policy (CSP) 的网页可能会阻止 WebAssembly 编译和执行模块。有关允许 WebAssembly 编译和执行的更多信息,请参阅 script-src CSP。
语法
WebAssembly.compile(bufferSource)
WebAssembly.compile(bufferSource, compileOptions)
参数
bufferSource
-
一个包含您要编译的 Wasm 模块的二进制代码的 类型化数组 或
ArrayBuffer
。 compileOptions
可选-
一个包含编译选项的对象。属性可以包括:
builtins
可选-
一个包含一个或多个字符串的数组,这些字符串允许在编译后的 Wasm 模块中使用 JavaScript 内置函数。这些字符串定义了您想启用的内置函数。目前唯一可用的值是
"js-string"
,它启用 JavaScript 字符串内置函数。 importedStringConstants
可选-
一个字符串,指定 导入的全局字符串常量 的命名空间。如果您希望在 Wasm 模块中使用导入的全局字符串常量,则需要指定此属性。
返回值
一个 Promise
,它解析为一个表示已编译模块的 WebAssembly.Module
对象。
异常
- 如果
bufferSource
不是 类型化数组 或ArrayBuffer
,则 Promise 会以TypeError
拒绝。 - 如果编译失败,Promise 会以
WebAssembly.CompileError
拒绝。
示例
使用 compile
下面的示例使用 compile()
函数编译加载的 simple.wasm 字节码,然后使用 postMessage() 将其发送到 worker。
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!"
打印到控制台)。在线查看此示例。
const importObject = {
// Regular import
m: {
log: console.log,
},
};
const compileOptions = {
builtins: ["js-string"], // Enable JavaScript string builtins
importedStringConstants: "string_constants", // Enable imported global 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());
规范
规范 |
---|
WebAssembly JavaScript 接口 # dom-webassembly-compile |
浏览器兼容性
加载中…