Broccoli Tastes Good!


posted by qmx on 01 September 2014

On our last post we were talking about the broccoli-static-compiler. One of the things I didn’t mention was that you need to narrow down your file selections better.

Web Performance

It’s no news that if you want any Web Page or Web App to load fast, preprocessing files is a must. This is where broccoli actually shines. It’s dead easy to add steps to your build process. Let’s start with…

Concatenating

I’ve added jquery as a dependency to our app. Now for educational purposes let’s add lodash as a dependency too.

broccoli-concat will take care of cramming the two deps together into a deps.js file.

var concat = require('broccoli-concat');

//....

var concatenatedDeps = concat(deps, {
    inputFiles: [
        'jquery/dist/jquery.js',
        'lodash/dist/lodash.js'
    ],
    outputFile: '/assets/deps.js'
});

var tree = mergeTrees([concatenatedDeps, 'app', 'public']);

Note here that we stopped including deps on the last mergeTrees call - we only want to pass the produced output forward. If you try to access any of the deps under bower_components, it’ll 404 now.

Minifying

Now let’s try to trim this down a little bit. broccoli-uglify-js comes to the rescue.

var uglifyJS = require('broccoli-uglify-js');

//....

concatenatedDeps = uglifyJS(concatenatedDeps);

That’s it! Another nice size reduction (for jquery + lodash it goes from 450k to 181k!)

Environment-Specific Optimizations

Sometimes you want to do something, but only for production. A good example for this is asset fingerprinting, like Rails Poopline does.. broccoli-env comest to the rescue.

var env = require('broccoli-env').getEnv();

//....

if(env === 'production') {
    // do stuff
}

The environment can be set by using the env var BROCCOLI_ENV.

A good example for this is using broccoli-asset-rev, but only for production since it breaks livereload.

WARNING: it breaks livereload. You’ve been warned.

var assetRev = require('broccoli-asset-rev');

//....

if (env === 'production') {
    tree = assetRev(tree);
}

If everything works fine, you’ll end up with something like /assets/deps-<long hash>.js inside your served html.

Intermission!

Enjoying it? Stay tuned for more!

The amazing fractal broccoli was taken from wikicommons