WebAssembly (Wasm) 編譯
Dart 團隊很高興能將 WebAssembly 新增為編譯目標,以便為 Web 建置 Dart 和 Flutter 應用程式。
WebAssembly 支援的開發仍在進行中,這可能會導致頻繁的變更。請重新瀏覽此頁面以取得最新更新。
WebAssembly 支援
#目前版本的 Dart 編譯為 WebAssembly 有一些限制
它以具有垃圾回收 (Garbage Collection, WasmGC) 的 WebAssembly 為目標,因此並非所有瀏覽器目前都支援。目前支援的瀏覽器清單可在 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 編譯在穩定版中提供,但仍處於預覽階段。在我們持續最佳化工具以改善開發人員體驗的同時,您今天可以按照此處概述的暫時步驟,嘗試將 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。 檢視原始碼 或 回報問題。