WebAssembly (Wasm) 編譯
Dart 團隊很高興將 WebAssembly 新增為構建用於 Web 的 Dart 和 Flutter 應用的編譯目標。
WebAssembly 支援的開發仍在進行中,這可能會導致頻繁更改。請重新訪問此頁面以獲取最新更新。
WebAssembly 支援
#當前版本的 Dart 編譯到 WebAssembly 有一些限制
它面向帶有垃圾回收的 WebAssembly (WasmGC),因此並非所有瀏覽器目前都支援。當前支援的瀏覽器列表可在Flutter 文件中檢視。
編譯後的 Wasm 輸出目前面向 JavaScript 環境(例如瀏覽器),因此當前不支援在 wasmtime 和 wasmer 等標準 Wasm 執行時中執行。詳情請參閱 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.dartWasm 編譯功能已在穩定版中可用,但仍處於預覽階段。在我們繼續最佳化工具以改善開發者體驗的同時,你今天就可以按照此處概述的臨時步驟嘗試將 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(文件)
你也可以在此處嘗試這個小示例。