dart2js
- Dart course
- Advanced
- Lesson 49/83
- 5 min
Learn JavaScript compilation with dart2js.
dart2js
dart2js is the tool that compiles Dart code to JavaScript. This way code you write in Dart runs in the browser. You compile with dart compile js main.dart -o main.js; the output is a .js file.
dart2js does tree-shaking: it leaves unused code out of the output. It produces minified output for production. This is the classic path to bring Dart to the web; older than dart2wasm but still common.
The compile command
You call dart2js with the dart compile js command. Example: dart compile js main.dart -o main.js. This takes main.dart and produces main.js. You include this file in an HTML page with a <script> tag.
During compilation dart2js drops unused library parts (tree-shaking). This keeps the output small. In production you can minify at -O4 level; during development you prefer more readable output.
Practice Print dart2js info
In main add print('dart2js: Dart → JavaScript') and print('Output: main.js'). This is static info summarizing what dart2js does.
Starter code
void main() {
// print dart2js info
}Sample solution
void main() {
print('dart2js: Dart → JavaScript');
print('Output: main.js');
}Expected output
dart2js: Dart → JavaScript Output: main.js
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does dart2js produce?
- JavaScript Correct answer
- WebAssembly
- Python code
- C++ code
Explanation: dart2js produces JavaScript from Dart code.
2 The dart2js output extension
dart compile js main.dart -o main.____;
dart compile js main.dart -o main.js;
Explanation: dart2js produces a .js JavaScript file.
3 Match the dart2js parts
| Term | Meaning |
|---|---|
dart2js |
Dart → JavaScript |
dart compile js |
Compile command |
main.js |
Output file |
tree-shaking |
Drops unused code |