WebAssembly (Wasm) 编译
Dart 团队很高兴在为 Web 构建 Dart 和 Flutter 应用时,将 WebAssembly 添加为编译目标。
WebAssembly 支持的开发仍在进行中,这可能会导致频繁的更改。请重新访问此页面以获取最新更新。
WebAssembly 支持
#当前版本的 Dart 编译到 WebAssembly 有许多限制
它以带有垃圾回收的 WebAssembly (WasmGC) 为目标,因此并非所有浏览器都受支持。当前支持的浏览器列表可在 Flutter 文档中找到。
编译后的 Wasm 输出当前以 JavaScript 环境(如浏览器)为目标,因此目前不支持在标准 Wasm 运行时(如 wasmtime 和 wasmer)中执行。有关详细信息,请参阅issue #53884
编译为 Wasm 时,仅支持 Dart 的 下一代 JS 互操作机制。
webdev
工具目前不支持运行 (webdev serve
) 或构建 (webdev build
)。以下步骤包含临时解决方法。有关详细信息,请参阅 webdev issue 2206。
支持的包
#要查找 Wasm 兼容的包,请在 pub.dev 上使用 wasm-ready
过滤器。
如果一个包没有导入不兼容 Wasm 的库(如 dart:html
、dart:js
等),则它就是“wasm-ready”的。你可以在 JS 互操作页面上找到不允许的库的完整列表。
将你的 Web 应用编译为 Wasm
#我们已经在 dart
CLI 中实现了支持,用于在 Dart 和 Flutter 中调用 Wasm 编译器
$ dart help compile wasm
Compile Dart to a WebAssembly/WasmGC module.
Usage: dart compile wasm [arguments] <dart entry point>
-h, --help Print this usage information.
-o, --output Write the output to <file name>.
This can be an absolute or relative path.
-v, --verbose Print debug output during compilation
--enable-asserts Enable assert statements.
-D, --define=<key=value> Define an environment declaration. To specify multiple declarations, use multiple
options or use commas to separate key-value pairs.
For example: dart compile wasm -Da=1,b=2 main.dart
Wasm 编译在 stable 版本中可用,但仍处于预览阶段。在我们继续优化工具以改善开发者体验的同时,你可以按照此处概述的临时步骤,立即尝试将 Dart 编译为 Wasm
从一个 Web 应用开始:
dart create -t web mywebapp
该模板使用
package:web
创建一个小型的 Web 应用,这对于运行 Wasm 是必要的。请确保你的 Web 应用已从dart:html
迁移到package:web
。使用 Wasm 编译到新的
site
输出目录:mywebapp$ dart compile wasm web/main.dart -o site/main.wasm
复制 Web 文件:
cp web/index.html web/styles.css site/
创建一个 JS 引导文件来加载 Wasm 代码
添加一个新文件
site/main.dart.js
,并用此main.dart.js
示例的内容填充它。提供输出:
dart pub global run dhttpd
(文档)
你也可以尝试这个小例子 here。
除非另有说明,否则本网站上的文档反映的是 Dart 3.7.1 版本。页面上次更新于 2024-06-17。 查看源代码 或 报告问题。