dart2js compiler translates Dart code into optimized JavaScript for deployment in web browsers. It’s designed for production use, offering aggressive optimizations including tree-shaking, minification, and deferred loading.
Overview
dart2js is a whole-program compiler that performs global analysis and optimization to produce fast, compact JavaScript output. Unlike dartdevc, which prioritizes development speed, dart2js focuses on production-ready output with minimal file size and maximum runtime performance.
Architecture
The compiler operates in several phases:- Common Front-End - Parsing, type checking, and Kernel AST generation
- Tree-Shake and Create World - Determine reachable code using Rapid Type Analysis (RTA)
- Global Analysis - Type inference and data flow analysis across method boundaries
- Code Generation - Build SSA graph, optimize, and emit JavaScript
- Link Tree-Shake - Second round of tree-shaking after optimizations
- Emit JavaScript - Assemble final program with minified names
Basic Usage
Command Line
Compile a Dart application to JavaScript:Common Options
| Option | Description |
|---|---|
-o, --output=<file> | Output file path |
-O0, -O1, -O2, -O3, -O4 | Optimization level (default: O2) |
--minify | Minify output (enabled by default in production) |
--no-minify | Disable minification |
--no-source-maps | Don’t generate source maps |
-D<name>=<value> | Define environment variable |
Optimization Levels
- O0 - No Optimization
- O1 - Size Optimization
- O2 - Default
- O3 - Speed Optimization
- O4 - Maximum Optimization
Minimal optimization for debugging:
- Fastest compilation
- Largest output size
- Best for debugging
- Preserves code structure
Advanced Features
Deferred Loading
Split your application into smaller chunks that load on demand:app.js- Main bundleapp.js_1.part.js- Deferred chunk for heavy_library
Source Maps
Generate source maps for debugging:app.js- Compiled JavaScriptapp.js.map- Source map for debugging
Environment Variables
Define compile-time constants:Compiler Pragmas
dart2js supports pragmas to control compilation behavior:Inline Control
Runtime Checks
Optimization Hints
Performance Tips
Tree-Shaking
dart2js automatically removes unused code. Help it by:Type Annotations
Provide types for better optimization:Avoid Dynamic
Dynamic calls prevent optimization:Debugging Compiled Output
Analyze Output Size
Use dump-info to understand code size:Readable Output
Generate more readable JavaScript:Migration from dart2js Command
Legacydart2js command is deprecated. Use dart compile js instead:
- Old (Deprecated)
- New (Recommended)
Limitations
- No dart:io - JavaScript runtime doesn’t support file system operations
- No dart:mirrors - Reflection is not supported for code size reasons
- No dart:ffi - Foreign Function Interface unavailable in JavaScript
- Integer precision - JavaScript numbers are 64-bit floats; use
BigIntfor large integers