目錄

WebAssembly (Wasm) 編譯

Dart 團隊很高興能在為網頁建置 Dart 和 Flutter 應用程式時,新增 WebAssembly 作為編譯目標。

WebAssembly 支援的開發仍在進行中,這可能會導致頻繁的變更。請重新造訪此頁面以取得最新更新。

WebAssembly 支援

#

目前版本的 Dart 編譯為 WebAssembly 有許多限制

  1. 它以具有垃圾收集的 WebAssembly (WasmGC) 為目標,因此目前並非所有瀏覽器都支援。目前支援的瀏覽器清單可在 Flutter 文件中找到。

  2. 編譯的 Wasm 輸出目前以 JavaScript 環境(例如瀏覽器)為目標,因此目前不支援在標準 Wasm 執行階段(如 wasmtime 和 wasmer)中執行。如需詳細資訊,請參閱 issue #53884

  3. 編譯為 Wasm 時,僅支援 Dart 的下一代 JS 互通機制

  4. webdev 工具目前不支援執行 (webdev serve) 或建置 (webdev build)。下列步驟包含暫時的解決方法。如需詳細資訊,請參閱 webdev issue 2206

支援的套件

#

若要尋找與 Wasm 相容的套件,請在 pub.dev 上使用 wasm-ready 篩選器。

如果套件沒有匯入不符合 Wasm 規範的函式庫(例如 dart:htmldart:js 等),則該套件為「wasm-ready」。您可以在JS 互通頁面上找到不允許的完整函式庫清單。

將您的網頁應用程式編譯為 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

  1. 從網頁應用程式開始:dart create -t web mywebapp

    範本會使用 package:web 建立一個小型網頁應用程式,這是執行 Wasm 所必需的。請確保您的網頁應用程式已從 dart:html 遷移package:web

  2. 使用 Wasm 編譯到新的 site 輸出目錄:mywebapp$ dart compile wasm web/main.dart -o site/main.wasm

  3. 複製網頁檔案:cp web/index.html web/styles.css site/

  4. 建立一個 JS 啟動程式檔案以載入 Wasm 程式碼

    新增一個檔案 site/main.dart.js,並使用這個 main.dart.js 範例的內容填入。

  5. 提供輸出:dart pub global run dhttpd (文件)

您也可以在這裡試用這個小範例 這裡