dart2js: The Dart-to-JavaScript Compiler
You can use the dart2js tool to compile Dart
code to JavaScript. Dart Editor
uses dart2js behind the scenes whenever Dart Editor compiles to
JavaScript. This section tells you how to use dart2js on the command line.
It also give tips on debugging the JavaScript that dart2js
generates.
Here’s an example of compiling a Dart file to JavaScript:
$DART_SDK/bin/dart2js --out=test.js test.dart
This command produces a file that contains the JavaScript
equivalent of your Dart code. It also produces a source map, which can
help you debug the JavaScript version of the app more easily.
Common command-line options for dart2js include:
-o<file> or
--out=<file>Generate the output into
<file>. If not specified, the
output goes in a file named out.js.
-c
or --checkedInsert runtime type checks, and enable assertions (checked
mode).
--minifyGenerate minified output.
--disallow-unsafe-evalDisable dynamic generation of code in the output. Use this
option when you want the generated JavaScript to satisfy CSP
restrictions. For more information, see An
Introduction to Content Security Policy.
-h
or --helpDisplay help. (Use -vh
for information about all options.)
--output-type=dartOutput Dart code instead of JavaScript. This option is
useful when deploying your app, because it generates a single file
containing everything the app needs.
Helping dart2js Generate Better Code
You can do a couple of things to improve the code that dart2js
generates:
Write your code in a way that makes type inference
easier.
Once you’re ready to deploy your app, use the dart2js --minify
option to reduce code size.
Note
Don’t worry about the size of your app’s included libraries.
Thanks to a feature called tree shaking, dart2js
omits unused classes, functions, methods, and so on. Just import the
libraries you need, and let dart2js get rid of what you don’t
need.
Follow these practices to help dart2js do better type inference,
so it can generate smaller and faster JavaScript code:
Avoid setting variables to null.
Use const or final variables wherever possible.
Be consistent with the types of arguments you pass into each
function or method.
This section gives tips for debugging dart2js-produced code in
Chrome, Firefox, and Safari. Debugging the JavaScript produced by
dart2js is easiest in browsers such as Chrome that support source
maps.
Whichever browser you use, you should enable pausing on at least
uncaught exceptions, and perhaps on all exceptions. For frameworks such
as dart:isolate and dart:async that wrap user code in try-catch, we
recommend pausing on all exceptions.
Firefox doesn’t yet support source maps (see bug
#771597). To debug in Firefox: