dart2wasm compiler translates Dart code into WebAssembly (Wasm) modules for modern web browsers. It offers near-native performance and compact binary size, making it ideal for compute-intensive web applications.
Overview
dart2wasm compiles Dart to WebAssembly, a portable, low-level binary format designed for efficient execution in web browsers. WebAssembly provides:
- Near-native performance - Faster than JavaScript for CPU-intensive tasks
- Compact binaries - Smaller than equivalent JavaScript
- Predictable performance - No JIT compilation overhead
- Memory safety - Sandboxed execution environment
Browser Support
WebAssembly is supported in all modern browsers:- Chrome/Edge 91+
- Firefox 89+
- Safari 15+
Basic Usage
Command Line
Compile a Dart application to WebAssembly:output.wasm- WebAssembly binaryoutput.mjs- JavaScript loader module
Common Options
| Option | Description |
|---|---|
-o, --output=<file> | Output file path (*.wasm) |
-O0, -O1, -O2, -O3, -O4 | Optimization level |
--no-minify | Don’t minify imports/exports |
--enable-asserts | Enable assert statements |
-D<name>=<value> | Define environment constant |
Building and Testing
Local Development
For rapid iteration during development:-g flag preserves the name section for debugging and profiling.
Using the SDK
With a built Dart SDK:Optimization Levels
- O0 - Debug Build
- O1 - Size Optimized
- O2 - Balanced
- O3 - Speed Optimized
- O4 - Maximum
No optimizations, fast compilation:
- Fastest compilation
- Largest binary size
- Best for debugging
- No wasm-opt passes
Loading WebAssembly
Using the Generated Loader
The compiler generates a JavaScript module loader:Custom Imports and Exports
Define JavaScript interop:Wasm Detection
Detect if code is running as WebAssembly:Inspecting Wasm Output
Disassemble to WAT
Convert binary Wasm to text format:Analyze Binary Size
Testing
Run dart2wasm test suite:Benchmarking
Performance Testing
Comparing with JavaScript
- WebAssembly
- JavaScript
Advanced Configuration
Compiler Options
Pass extra options to the compiler:Running from Source
Develop the compiler itself:Platform-Specific Builds
V8 (Chrome/Node.js)
Optimize for V8:Flutter Web (HHH)
For Flutter web integration: See flutter_hhh_builds.md for Flutter-specific build instructions.Limitations
- No dart:io - File system operations not available in browser
- No dart:mirrors - Reflection not supported
- No dart:ffi - FFI only works in native environments
- GC proposal required - Needs browsers with WebAssembly GC support
- Experimental - API and features may change
Performance Characteristics
- Startup time: Faster than dart2js in most cases
- Execution speed: Near-native for compute-intensive tasks
- Binary size: Smaller than equivalent JavaScript
- Memory usage: Efficient with WebAssembly linear memory