HTML: Markup language
CSS: Styling language
JavaScript: Scripting language
Web APIs: Programming interfaces
All web technology
Learn web development
Discover our tools
Get to know MDN better
此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
View in English Always switch to English
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2017年10月.
* Some parts of this feature may have varying levels of support.
WebAssembly.compile() 静态方法将 WebAssembly 二进制代码编译为一个 WebAssembly.Module 对象。如果在实例化模块之前必须要对其进行编译,那么这个函数很有帮助(否则,应该使用 WebAssembly.instantiate() 函数)。
WebAssembly.compile()
WebAssembly.Module
WebAssembly.instantiate()
备注:有严格内容安全策略(CSP)的网页可能会阻止 WebAssembly 编译和执行模块。与允许 WebAssembly 编译和执行有关的额外信息,参见 script-src CSP。
WebAssembly.compile(bufferSource) WebAssembly.compile(bufferSource, compileOptions)
bufferSource
一个类型化数组或 ArrayBuffer,包含你想编译的 Wasm 模块的二进制代码。
ArrayBuffer
compileOptions
一个编译选项的对象。属性包括:
builtins
一个由一个或多个字符串组成的数组,用于在编译的 Wasm 模块中启用 JavaScript 内置功能。字符串定义你想启用的内置功能。当前,唯一可用的值是 "js-string",启用的是 JavaScript 字符串内置功能。
"js-string"
importedStringConstants
一个字符串,为导入的全局字符串常量指定命名空间。如果你希望在 Wasm 模块中使用导入的全局字符串常量,就需要指定这个属性。
一个 Promise,兑现为表示已编译模块的 WebAssembly.Module 对象。
Promise
TypeError
WebAssembly.CompileError
下面的例子使用 compile() 函数编译加载的 simple.wasm 字节码,然后使用 postMessage() 将其发送给一个 worker。
compile()
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() 效率更高。
WebAssembly.compileStreaming()
这个例子在用 compile() 编译 Wasm 模块时,启用 JavaScript 字符串内置功能和导入的全局字符串常量,然后用 instantiate() 将其实例化,接着运行导出的 main() 函数(其向控制台打印 "hello world!")。查看其在线版本。
instantiate()
main()
"hello world!"
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());
Enable JavaScript to view this browser compatibility table.