I Shrunk my Dart-to-JS code by 11X and So Can You

Dart, the structured and scalable programming language for web apps, compiles to JavaScript thanks to dart2js. This means Dart apps run across the modern web. When you compile to JavaScript, you want to ensure dart2js generates the smallest amount of bytes. Less bytes means smaller bandwidth bills, and faster load times, and longer battery life. All good things! Read on to learn how to minify your generated JavaScript.

For this example, I will use the offline-enabled Todo app that I built to highlight Lawndart, my easy library for browser storage. The Todo app uses quite a few libraries:
  • dart:html
  • Lawndart
  • WebSQL
  • IndexedDB
  • Local storage
  • Web UI
The original generated JavaScript output size was 612,249 bytes. Minified, it became 289,840 bytes. Minified and gzipped it became 56,496 bytes. That's about 11X smaller than the original output!

(Measuring the original size of the code is tricky. Do I count the lines that I wrote? Do I count the lines generated by the Web UI compiler? I count 9,313 bytes of generated Dart code from the Web UI compiler, which is the code that would be shipped down to Dartium during development. This does not count the size of the packages required. Also, most developers would run a tree-shaking tool on the Dart code if they want to ship pure Dart in production. When I ran dart2dart to generate a single file that contained all the Dart code required for the app, I ended up with 44,860 bytes unminified and ungzipped.)

Let's learn how to get compiled JavaScript output as small as possible.

Step One: Turn on Minification

The editor does not ship with minification turned on by default. Say what?! Fear not, we can fix that.

  1. Right click on your project
  2. Select properties
  3. Select Dart Settings
  4. Add --minify to "Additional flags:"
  5. Embrace the smallification
See this in action:



(Here's a bug that requests to make this easier, please star!)

If you don't use Dart Editor, you can also minify from the command line. Here is an example:

dart2js --minify --out=app.js app.dart

The file shrinks to 289,840 bytes with minification, a 2.1X shrinkage!

Step Two: Compress the file on-the-fly

Most web servers will compress your files for you, on the fly! See your web server's configuration for more details.

The file shrinks to 56,496 bytes with gzip, a 11X shrinkage from the original!

Step Three: There is no step three!

Yup, just use --minify with dart2js and be sure your server has turned on compression/gzip.

To be sure, we're not yet happy with the output size and we're working hard to generate even smaller code. However, minification really helps and you should use it today. Please file bugs and feature requires at dartbug.com. Thanks!

Popular posts from this blog

The 29 Healthiest Foods on the Planet

Lists and arrays in Dart

Converting Array to List in Scala