Compiling to WebAssembly
suggest changeBesides JavaScript, Dart can compile web apps to WebAssembly (Wasm). The compiler is called dart2wasm and you run it with dart compile wasm. It has been stable since Dart 3.3, and flutter build web --wasm uses it too.
dart2wasm targets WasmGC, the garbage-collection extension of WebAssembly. Dart objects are Wasm GC structs that the browser's own garbage collector manages, so the output doesn't include a memory allocator or a GC. That keeps modules small, and Dart objects and JavaScript objects can reference each other without leaking.
This article covers:
- compiling, the generated files, and running the output in Node.js and in a browser
- falling back to JavaScript when the browser doesn't support WasmGC
- how the semantics differ from dart2js (64-bit
int, doubles, unsupported libraries) - detecting Wasm at compile time and with conditional imports
- calling Dart from JavaScript
- optimization levels, code size, stack traces and performance
- deferred loading, and running tests compiled to Wasm
The examples were run with Dart 3.13.4, Node.js 24 and headless Microsoft Edge 155.
Browser requirements
dart2wasm needs WasmGC, the JS String Builtins proposal, and the final (phase 4) exception handling proposal, which provides WebAssembly.JSTag. According to dart.dev that means:
| Browser | Minimum version |
|---|---|
| Chrome, Edge and other Chromium browsers | 137 |
| Firefox | 134 (147 for Flutter web) |
| Safari (macOS and iOS) | 26.2 |
| Node.js | 24 |
For older browsers, you also build the app with dart2js and load the JavaScript build instead, as shown below.
Hello, Wasm
void main() {
print('Hello from WebAssembly!');
const isWasm = bool.fromEnvironment('dart.tool.dart2wasm');
print('dart2wasm: $isWasm');
}
Compile it:
dart compile wasm hello.dart -o out/hello.wasm
Generated wasm module 'out/hello.wasm', and JS init file 'out/hello.mjs'.
The output directory now contains four files:
| File | Size | What it is |
|---|---|---|
hello.wasm |
1,874 bytes | the compiled program |
hello.mjs |
6,206 bytes | a JavaScript module that compiles and instantiates the .wasm file and provides the imports it needs (printing, strings, numbers formatting) |
hello.support.js |
200 bytes | a single JavaScript expression that checks whether the engine supports the Wasm features the module needs |
hello.wasm.map |
3,942 bytes | a source map (skip it with --no-source-maps) |
A .wasm file can't run on its own. Something has to load it through hello.mjs, which exports two functions:
compileStreaming(response)compiles from afetch()response (browsers)compile(bytes)compiles from the bytes of the file (Node.js, or bytes you already have)
Both return an app object. You call instantiate() on it, then invokeMain() on the result.
Running Wasm in Node.js
Node.js 24 supports everything dart2wasm needs. This small runner script loads any compiled program and passes command-line arguments to main:
// run.mjs. Usage: node run.mjs out/hello.mjs [args...]
import { readFile } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
const [loaderPath, ...args] = process.argv.slice(2);
const wasmPath = loaderPath.replace(/\.mjs$/, '.wasm');
const loader = await import(pathToFileURL(loaderPath).href);
const app = await loader.compile(await readFile(wasmPath));
const instance = await app.instantiate({});
instance.invokeMain(...args);
node run.mjs out/hello.mjs
Hello from WebAssembly!
dart2wasm: true
pathToFileURL matters on Windows: import('C:\\...') fails because C: is read as a URL scheme.
The arguments given to invokeMain(...) become main's List<String> args. Running Dart in Node.js like this is handy for quick checks and tests, but dart:io doesn't work under dart2wasm (see below), so it isn't a way to write Node.js servers.
A web app
A real web app uses the DOM through package:web and dart:js_interop. Create a project with dart create -t web wasmapp, or write a pubspec.yaml by hand:
name: wasmapp
publish_to: none
environment:
sdk: ^3.13.0
dependencies:
web: ^1.1.1
dev_dependencies:
lints: ^6.0.0
web/main.dart changes the page and reports which compiler built it:
import 'dart:js_interop';
import 'package:web/web.dart' as web;
const isWasm = bool.fromEnvironment('dart.tool.dart2wasm');
void main() {
final output = web.document.querySelector('#output') as web.HTMLDivElement;
final compiler = isWasm ? 'WebAssembly (dart2wasm)' : 'JavaScript (dart2js)';
output.textContent = 'Compiled to $compiler';
// 2^62 fits in a 64-bit int, but not exactly in a JavaScript number.
final big = 1 << 62;
final p = web.HTMLParagraphElement()..textContent = '1 << 62 = $big';
web.document.body!.append(p);
var clicks = 0;
final button = web.HTMLButtonElement()..textContent = 'Click me';
button.onClick.listen((_) {
clicks++;
button.textContent = 'Clicked $clicks times';
});
web.document.body!.append(button);
web.console.log('main() finished'.toJS);
}
web/index.html loads one small module script:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dart and Wasm</title>
<script type="module" src="bootstrap.js"></script>
</head>
<body>
<div id="output">Loading...</div>
</body>
</html>
web/bootstrap.js loads the Wasm build when the browser supports it, and the JavaScript build otherwise:
// Loads main.wasm when the browser supports it, otherwise main.js.
async function wasmSupported() {
// main.support.js is generated by dart compile wasm: a single
// expression that checks for the Wasm features the module needs.
const check = await (await fetch('main.support.js')).text();
return (0, eval)(check) && 'JSTag' in WebAssembly;
}
const forceJs = new URLSearchParams(location.search).has('js');
if (!forceJs && await wasmSupported()) {
const { compileStreaming } = await import('./main.mjs');
const app = await compileStreaming(fetch('main.wasm'));
const instance = await app.instantiate({});
instance.invokeMain();
} else {
const script = document.createElement('script');
script.src = 'main.js';
document.head.append(script);
}
main.support.js checks for WasmGC and SIMD. The module also imports WebAssembly.JSTag, so the script checks for that as well; without the extra check, a browser with WasmGC but older exception handling would fail at instantiate(). If your Content Security Policy forbids eval, copy the expression from main.support.js into the script instead. The ?js query parameter forces the JavaScript build, which is useful for testing the fallback.
Build both versions into a site directory:
mkdir -p site
dart compile wasm -O2 web/main.dart -o site/main.wasm
dart compile js -O2 web/main.dart -o site/main.js
cp web/index.html web/bootstrap.js site/
webdev serve and webdev build don't support Wasm, which is why these steps are done by hand.
Serving the files
The server must send .wasm files as application/wasm. Otherwise WebAssembly.compileStreaming rejects the response with a "wrong MIME type" error. .mjs and .js must be served as text/javascript, because browsers refuse to run module scripts with any other type. Many simple servers get this wrong. On Windows, Python's http.server serves .mjs as text/plain.
The dhttpd package serves both correctly:
dart run dhttpd@ --path site --port 0
dart run package@ (Dart 3.12) runs the latest version of a package without adding it to your project. --port 0 picks a free port, which dhttpd prints at startup. Check the headers:
curl -sI http://localhost:47913/main.wasm | grep -i content-type
curl -sI http://localhost:47913/main.mjs | grep -i content-type
content-type: application/wasm
content-type: text/javascript
Loading the page in headless Edge and dumping the resulting DOM shows that each build ran:
msedge --headless --virtual-time-budget=5000 --dump-dom http://localhost:47913/
msedge --headless --virtual-time-budget=5000 --dump-dom "http://localhost:47913/?js"
<div id="output">Compiled to WebAssembly (dart2wasm)</div>
<p>1 << 62 = 4611686018427387904</p><button>Click me</button>
...
<div id="output">Compiled to JavaScript (dart2js)</div>
<p>1 << 62 = 0</p><button>Click me</button>
(Output shortened to the interesting lines.) The two builds give different results for 1 << 62, which leads to the biggest semantic difference.
In production, also compress the files (.wasm compresses to about 40% of its size with gzip) and serve them with long cache lifetimes. Put a version or hash in the file names, because main.mjs and main.wasm have to come from the same build.
What changes compared to JavaScript
dart2wasm follows the Dart VM's semantics. dart2js maps Dart numbers to JavaScript numbers. Code that works on the VM therefore usually works the same under Wasm, and differences show up between the two web compilers.
Numbers
This program parses its inputs at run time, so the compiler can't compute the results ahead of time:
void main() {
// Parse at run time so the compiler can't fold the expressions.
final one = int.parse('1');
final oneDouble = double.parse('1');
final odd = int.parse('9007199254740993'); // 2^53 + 1
final max = int.parse('9223372036854775807'); // 2^63 - 1
print('1 << 62 ${one << 62}');
print('2^53 + 1 $odd');
print('max + 1 ${max + one}');
print('-1 >>> 60 ${-one >>> 60}');
print('~0 ${~(one - 1)}');
print('1.0 $oneDouble');
print('1.0 is int ${(oneDouble as Object) is int}');
print('identical(1, 1.0) ${identical(one, oneDouble)}');
print('runtimeType ${oneDouble.runtimeType}');
print('1e21.toInt() ${1e21.toInt()}');
}
dart run numbers.dart
dart compile wasm numbers.dart -o out/numbers.wasm && node run.mjs out/numbers.mjs
dart compile js -O2 numbers.dart -o out/numbers.js && node out/numbers.js
Dart VM and WebAssembly (identical output):
1 << 62 4611686018427387904
2^53 + 1 9007199254740993
max + 1 -9223372036854775808
-1 >>> 60 15
~0 -1
1.0 1.0
1.0 is int false
identical(1, 1.0) false
runtimeType double
1e21.toInt() 9223372036854775807
JavaScript:
1 << 62 0
2^53 + 1 9007199254740992
max + 1 9223372036854776000
-1 >>> 60 0
~0 4294967295
1.0 1
1.0 is int true
identical(1, 1.0) true
runtimeType int
1e21.toInt() 1e+21
Under Wasm:
intis a 64-bit two's complement integer that wraps around on overflow. Bitwise operators work on all 64 bits.intanddoubleare different types, so1.0prints as1.0and isn't anint.Int64ListandUint64Listwork (they throwUnsupportedErrorunder dart2js).- Integer literals larger than 2^53 compile. dart2js rejects them:
Error: The integer literal 9007199254740993 can't be represented exactly in JavaScript.
Code that hashes, does checksums, or uses bit tricks can silently give different results under the two web compilers. The Bit manipulation article explains how to write bit code that's portable to dart2js. If you ship both builds, test both.
Numbers that cross into JavaScript become JavaScript numbers, though. An int above 2^53 loses precision when it's passed to JavaScript (see "Calling Dart from JavaScript" below).
Libraries
Only the new JS interop is supported: dart:js_interop, dart:js_interop_unsafe and package:web. The old web libraries don't compile:
// legacy_dom.dart
import 'dart:html';
void setTitle(String t) => document.title = t;
legacy_dom.dart:1:8: Error: Dart library 'dart:html' is not available on this platform.
import 'dart:html';
^
Context: The unavailable library 'dart:html' is imported through these packages:
legacy_dom.dart => dart:html
Detailed import paths for (some of) the these imports:
main.dart => legacy_dom.dart => dart:html
The import path tells you which dependency to replace. Libraries that don't compile under dart2wasm:
| Library | Use instead |
|---|---|
dart:html, dart:svg, dart:indexed_db, dart:web_audio, dart:web_gl |
package:web |
dart:js, dart:js_util, package:js (since Dart 3.10/3.11) |
dart:js_interop, dart:js_interop_unsafe |
dart:mirrors |
code generation |
dart:ffi |
(not available on the web) |
dart:io imports compile, but nothing in it works:
import 'dart:io';
void main() {
try {
print(File('pubspec.yaml').readAsStringSync().length);
} catch (e) {
print('${e.runtimeType}: $e');
}
}
UnsupportedError: Unsupported operation: _Namespace
Packages on pub.dev that compile with dart2wasm get a "WASM ready" tag. If a dependency still uses dart:html or package:js, look for a newer version or file an issue. The JavaScript interop with dart:js_interop article shows how to migrate.
Detecting Wasm
bool.fromEnvironment with these names is a compile-time constant, so the branch that isn't taken is removed from the output:
const libraries = {
'dart.library.io': bool.fromEnvironment('dart.library.io'),
'dart.library.html': bool.fromEnvironment('dart.library.html'),
'dart.library.js_interop': bool.fromEnvironment('dart.library.js_interop'),
'dart.library.ffi': bool.fromEnvironment('dart.library.ffi'),
'dart.tool.dart2js': bool.fromEnvironment('dart.tool.dart2js'),
'dart.tool.dart2wasm': bool.fromEnvironment('dart.tool.dart2wasm'),
};
void main() {
libraries.forEach((name, available) => print('${name.padRight(24)} $available'));
}
| Constant | VM | dart2js | dart2wasm |
|---|---|---|---|
dart.library.io |
true | false | false |
dart.library.html |
false | true | false |
dart.library.js_interop |
false | true | true |
dart.library.ffi |
true | false | false |
dart.tool.dart2js |
false | true | false |
dart.tool.dart2wasm |
false | false | true |
So:
dart.tool.dart2wasmtells you that you're compiled to Wasm. Flutter'skIsWasmconstant is based on it.dart.library.js_interopis true on both web compilers, so use it to choose web code.dart.library.htmlis false under Wasm, so don't use it to detect the web anymore.
The same names work in conditional imports, which is how a package provides different implementations per platform:
// main.dart
import 'platform_stub.dart'
if (dart.library.io) 'platform_io.dart'
if (dart.library.js_interop) 'platform_web.dart';
void main() {
print(platformName);
}
// platform_stub.dart
String get platformName => 'unknown';
// platform_io.dart
import 'dart:io';
String get platformName => 'native (${Platform.operatingSystem})';
// platform_web.dart
import 'dart:js_interop';
@JS('navigator.userAgent')
external String get _userAgent;
const _isWasm = bool.fromEnvironment('dart.tool.dart2wasm');
String get platformName =>
'${_isWasm ? 'Wasm' : 'JavaScript'} on ${_userAgent.split(' ').first}';
Running it on the VM, then compiled with dart2js and with dart2wasm (both run in Node.js):
native (windows)
JavaScript on Node.js/24
Wasm on Node.js/24
Calling Dart from JavaScript
dart2wasm doesn't export your Dart functions from the module directly. Instead, main hands them to JavaScript: convert a function with .toJS and store it in a JavaScript global (or pass it to a JavaScript function):
import 'dart:js_interop';
// Assigning to this external setter sets globalThis.fib.
@JS('fib')
external set _fib(JSFunction f);
@JS('fibString')
external set _fibString(JSFunction f);
int fib(int n) {
var (a, b) = (0, 1);
for (var i = 0; i < n; i++) {
(a, b) = (b, a + b);
}
return a;
}
void main() {
_fib = ((int n) => fib(n)).toJS;
_fibString = ((int n) => fib(n).toString()).toJS;
}
// use.mjs
import { readFile } from 'node:fs/promises';
import { compile } from './out/lib.mjs';
const app = await compile(await readFile('out/lib.wasm'));
const instance = await app.instantiate({});
instance.invokeMain(); // main() sets globalThis.fib and globalThis.fibString
console.log(fib(50));
console.log(fib(90));
console.log(fibString(90));
12586269025
2880067194370816000
2880067194370816120
fib(90) is computed exactly in Dart. When the result crosses into JavaScript it becomes a JavaScript number and loses its last digits. Pass large integers as strings or as a JavaScript BigInt. invokeMain doesn't wait for an async main, so do the setup before the first await.
Optimization levels and code size
-O selects one of five optimization levels:
| Level | Effect |
|---|---|
-O0 |
no optimizations, for debugging the compiler output |
-O1 |
default: optimizes with Binaryen's wasm-opt, keeps all checks and names |
-O2 |
also minifies class names. Use this for production. |
-O3 |
also omits implicit type checks, such as casts from dynamic and covariance checks |
-O4 |
also omits index bounds checks |
This program triggers each kind of check:
void main() {
final List<Object> items = [1, 'two'];
try {
final list = <int>[1, 2, 3];
print(list[int.parse('5')]);
} catch (e) {
print('index: ${e.runtimeType}');
}
try {
final n = items[int.parse('1')] as int;
print('cast passed: $n');
} catch (e) {
print('cast: ${e.runtimeType}');
}
try {
final dynamic d = items[int.parse('1')];
int i = d; // implicit cast from dynamic
print('implicit cast passed: $i');
} catch (e) {
print('implicit: ${e.runtimeType}');
}
List<num> nums = <int>[1, 2];
try {
nums.add(1.5); // covariance check
print('covariant add passed: $nums');
} catch (e) {
print('covariant: ${e.runtimeType}');
}
}
=== -O1
index: IndexError
cast: _TypeError
implicit: _TypeError
covariant: _TypeError
=== -O2
index: minified:Class105
cast: minified:Class107
implicit: minified:Class107
covariant: minified:Class107
=== -O3
index: minified:Class105
cast: minified:Class107
RuntimeError: illegal cast
at M (wasm://wasm/M-565afaee:wasm-function[18]:0x104a)
...
=== -O4
RuntimeError: array element access out of bounds
at M (wasm://wasm/M-1ce76c72:wasm-function[18]:0xf6b)
...
At -O2, runtimeType.toString() returns minified names, so never use it for logic or serialization. At -O3 and -O4, an error that would have been a catchable Dart exception becomes a Wasm trap, which kills the program and can't be caught. Some errors aren't caught at all: with the covariance check removed, nums.add(1.5) succeeds at -O3 and prints covariant add passed: [1, 2, 1.5], leaving a double inside a List<int>. The explicit as int cast is still checked at -O3. Only use these levels for code you've tested thoroughly, and only if they make a measurable difference.
Sizes for a 75-line benchmark program (shown in the next section) that uses JSON, sorting and string building:
| Level | Wasm | Wasm gzipped | dart2js | dart2js gzipped |
|---|---|---|---|---|
-O0 |
164,608 | 59,791 | 405,975 | 54,573 |
-O1 |
57,371 | 22,214 | 161,957 | 30,937 |
-O2 |
47,747 | 19,002 | 56,952 | 18,866 |
-O3 |
46,529 | 18,766 | 56,006 | 18,487 |
-O4 |
45,585 | 18,560 | 55,151 | 18,272 |
The web app above, at -O2, is 23,685 bytes of Wasm (9,869 gzipped) plus a 7,049-byte loader (2,327 gzipped), compared with 63,890 bytes of JavaScript (20,061 gzipped). Wasm files are smaller to download, and browsers compile them while they're still downloading.
Other ways to shrink the output:
- Use
-O2and serve with gzip or brotli. - Avoid code that defeats tree shaking, such as
dynamiccalls andnoSuchMethod. - Split rarely used features into deferred libraries (see below).
--no-source-mapsskips the.wasm.mapfile. Source maps aren't downloaded unless DevTools is open, so this only saves build output.--no-strip-wasmkeeps function names in the module (47,747 bytes become 63,806 for the benchmark). It's useful when debugging, not in production.
Stack traces
Stack traces show Wasm function indexes by default:
int parsePort(String s) => int.parse(s);
void main() {
try {
parsePort('http');
} catch (e, st) {
print(e);
print(st.toString().split('\n').take(3).join('\n'));
}
}
FormatException: Invalid radix-10 number (at character 1)
http
^
at M (wasm://wasm/M-0001c302:wasm-function[146]:0x6a64)
at M (wasm://wasm/M-0001c302:wasm-function[147]:0x6b6a)
at M (wasm://wasm/M-0001c302:wasm-function[20]:0x4496)
Compiled with --no-strip-wasm:
at M.int._handleFormatError (wasm://wasm/M-00024b92:wasm-function[146]:0x6a64)
at M.int._parseRadix (wasm://wasm/M-00024b92:wasm-function[147]:0x6b6a)
at M._invokeMain (wasm://wasm/M-00024b92:wasm-function[20]:0x4496)
parsePort is missing because it was inlined. In Chrome and Edge DevTools, the .wasm.map source map maps frames back to Dart files and lines, and you can set breakpoints in Dart source. For crash reports from production, log the raw trace and keep the source map of each release, as you would for minified JavaScript. See Stack traces for more.
Performance
This benchmark runs four kinds of work. Each is run once to warm up, then once timed:
import 'dart:convert';
class Point {
final double x, y;
Point(this.x, this.y);
double get dist2 => x * x + y * y;
}
int sieve(int n) {
final composite = List<bool>.filled(n + 1, false);
var count = 0;
for (var i = 2; i <= n; i++) {
if (composite[i]) continue;
count++;
for (var j = i * i; j <= n; j += i) {
composite[j] = true;
}
}
return count;
}
int fnv32(String s) {
var h = 0x811c9dc5;
for (final c in s.codeUnits) {
h = ((h ^ c) * 0x01000193) & 0xFFFFFFFF;
}
return h;
}
Object? jsonRoundTrip(int n) {
final data = [
for (var i = 0; i < n; i++)
{'id': i, 'name': 'item $i', 'tags': ['a', 'b', 'c'], 'price': i * 0.25},
];
final text = jsonEncode(data);
return (jsonDecode(text) as List).length;
}
int sortPoints(int n) {
var seed = 42;
double next() {
seed = (seed * 1103515245 + 12345) & 0x7FFFFFFF;
return seed / 0x7FFFFFFF;
}
final points = [for (var i = 0; i < n; i++) Point(next(), next())];
points.sort((a, b) => a.dist2.compareTo(b.dist2));
return points.length;
}
int strings(int n) {
final sb = StringBuffer();
for (var i = 0; i < n; i++) {
sb.write('line $i: ${i.toRadixString(16)}\n');
}
return fnv32(sb.toString());
}
void time(String name, Object? Function() body) {
body(); // warm up
final sw = Stopwatch()..start();
final result = body();
print('${name.padRight(8)} ${sw.elapsedMilliseconds.toString().padLeft(5)} ms ($result)');
}
void main() {
time('sieve', () => sieve(10000000));
time('json', () => jsonRoundTrip(200000));
time('sort', () => sortPoints(1000000));
time('strings', () => strings(1000000));
}
Results on one Windows machine. JavaScript and Wasm were built with -O2 and run in Node.js 24:
| Task | VM (JIT) | AOT exe | dart2js | dart2wasm |
|---|---|---|---|---|
| sieve | 200 ms | 157 ms | 310 ms | 192 ms |
| json | 569 ms | 560 ms | 1203 ms | 1203 ms |
| sort | 743 ms | 621 ms | 1498 ms | 704 ms |
| strings | 291 ms | 233 ms | 984 ms | 1161 ms |
Numbers varied by 20-40% between runs, but the pattern was stable:
- Integer loops and code that allocates objects were about twice as fast as JavaScript and close to native code. Typed fields,
intarithmetic and object allocation all map directly to Wasm. - String-heavy and JSON code was about as fast as JavaScript, or slower. Dart strings under dart2wasm are JavaScript strings accessed through imports, so each call crosses from Wasm into JavaScript.
- The
stringsresult differs: dart2js printed4210797624, the others602441583. Infnv32, the 32-bit by 25-bit product needs up to 57 bits, which a JavaScript number can't hold exactly. This is the number semantics difference again.
Calls between Dart and JavaScript, such as DOM access, have a cost under Wasm too. Keep hot loops inside Dart and cross the boundary in bigger chunks. As always, measure your own app in your target browsers. See Benchmarks and Performance.
Deferred loading
By default dart2wasm puts the whole program in one module, and loadLibrary() on a deferred import completes immediately. With the experimental --enable-deferred-loading flag, each deferred library becomes a separate .wasm file that's downloaded when loadLibrary() is called:
// report.dart
import 'dart:convert';
String buildReport(Map<String, int> sales) {
final total = sales.values.fold(0, (a, b) => a + b);
return const JsonEncoder.withIndent(' ').convert({
'total': total,
'sales': sales,
});
}
// main.dart
import 'report.dart' deferred as report;
Future<void> main() async {
print('app started');
await report.loadLibrary();
print(report.buildReport({'north': 120, 'south': 80}));
}
dart compile wasm -O2 --enable-deferred-loading main.dart -o out/main.wasm
This produces main.wasm (49,276 bytes) and main_module1.wasm (5,093 bytes). The loader can't know where your files are, so you pass a loadDeferredModules callback to instantiate. It receives the file names and a function that compiles and instantiates each one:
import { readFile } from 'node:fs/promises';
import { compile } from './out/main.mjs';
const app = await compile(await readFile('out/main.wasm'));
const instance = await app.instantiate({}, {
// Called by loadLibrary() with the names of the Wasm files it needs.
loadDeferredModules: async (moduleNames, loadModule) => {
await Promise.all(moduleNames.map(async (name) => {
console.log(`loading ${name}`);
await loadModule(name, await readFile(`out/${name}`));
}));
},
});
instance.invokeMain();
app started
loading main_module1.wasm
{
"total": 200,
"sales": {
"north": 120,
"south": 80
}
}
In a browser, pass a fetch() response, which is compiled while it streams. This page also shows the dartPrint hook: if a global dartPrint function exists, print calls it instead of console.log:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="module">
import { compileStreaming } from './main.mjs';
// print() calls dartPrint if it exists, otherwise console.log.
globalThis.dartPrint = (line) => {
document.querySelector('pre').textContent += line + '\n';
};
const app = await compileStreaming(fetch('main.wasm'));
const instance = await app.instantiate({}, {
loadDeferredModules: (names, loadModule) =>
Promise.all(names.map(async (name) => loadModule(name, await fetch(name)))),
});
instance.invokeMain();
</script>
</head>
<body><pre></pre></body>
</html>
The server log shows main_module1.wasm being requested after the main module started. Deferred loading under Wasm is still marked experimental, so test it with every SDK update. Lazily loading a library covers the deferred as syntax.
Testing with dart2wasm
package:test can compile tests with dart2wasm and run them in Node.js, Chrome or Firefox:
// test/int_test.dart
@TestOn('js || wasm')
library;
import 'package:test/test.dart';
const isWasm = bool.fromEnvironment('dart.tool.dart2wasm');
void main() {
test('ints are 64-bit', () {
final one = int.parse('1');
expect(one << 62, 4611686018427387904);
}, skip: isWasm ? false : 'needs 64-bit ints');
test('doubles print with a decimal point', () {
expect(double.parse('1').toString(), isWasm ? '1.0' : '1');
});
}
Run the tests with both web compilers in Node.js:
dart test -p node -c dart2js -c dart2wasm
00:00 +0: [Node.js, Dart2Wasm] test\int_test.dart: ints are 64-bit
00:00 +1: [Node.js, Dart2Wasm] test\int_test.dart: doubles print with a decimal point
00:04 +2: [Node.js, Dart2Js] test\int_test.dart: ints are 64-bit
Skip: needs 64-bit ints
00:04 +2 ~1: [Node.js, Dart2Js] test\int_test.dart: doubles print with a decimal point
00:04 +3 ~1: All tests passed!
In a browser, use -p chrome -c dart2wasm. The edge platform only supports dart2js, but Edge is Chromium-based, so you can use it as the chrome platform by setting CHROME_EXECUTABLE:
CHROME_EXECUTABLE="C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" dart test -p chrome -c dart2wasm
00:00 +0: [Chrome, Dart2Wasm] test\int_test.dart: ints are 64-bit
00:00 +1: [Chrome, Dart2Wasm] test\int_test.dart: doubles print with a decimal point
00:00 +2: All tests passed!
js and wasm in @TestOn are platform selectors: js matches dart2js and wasm matches dart2wasm. In CI, run both compilers if you ship both builds (see Testing in CI).
Flutter and standalone Wasm
- Flutter:
flutter build web --wasmbuilds with dart2wasm and generates a bootstrap that falls back to the JavaScript build in browsers without WasmGC.flutter run -d chrome --wasmruns it during development. The same library restrictions apply, so every plugin must usepackage:webanddart:js_interop. - Outside the browser:
--standaloneproduces a module that doesn't depend on JavaScript, for runtimes like Wasmtime. It still needs Dart-specific host imports, anddart:js_interopis not available in this mode. It's still experimental.
Summary
dart compile wasm -O2 web/main.dart -o site/main.wasmproducesmain.wasmplus themain.mjsloader. Load the loader withcompileStreaming(fetch('main.wasm')), then callinstantiate()andinvokeMain().- It requires WasmGC, JS string builtins and phase 4 exception handling: Chrome/Edge 137+, Firefox 134+, Safari 26.2+, Node.js 24. Use
main.support.jsplus aWebAssembly.JSTagcheck to fall back to a dart2js build. - Serve
.wasmasapplication/wasmand.mjsastext/javascript. intis 64-bit anddoubleis a separate type, as on the VM. Results can differ from dart2js, so test both builds if you ship both.- Only
dart:js_interopandpackage:webare supported.dart:html,dart:js,dart:js_utilandpackage:jsdon't compile, anddart:iothrows at run time. - Detect Wasm with
bool.fromEnvironment('dart.tool.dart2wasm'), and the web in general withdart.library.js_interop. - Use
-O2for production.-O3and-O4turn some Dart errors into uncatchable traps. - Numeric and object-heavy code gains the most. String-heavy code runs at about JavaScript speed.