Blog
Learning material for professionals eager to explore the science behind building a successful online product

#ASKTHEINDUSTRY 33: How do you Tree Shake with rollup?

Yet another piece of knowledge I’ve stolen from the Media Player Paul Lewis is building in the open. You can find it here. I highly recommend that you go and dissect it to learn how to structure and build a fairly sized PWA in 2017.

It is one of the simplest way I’ve found to drop in rollup in your project. First, of course, you install rollup.

npm install rollup

Then you create your script to configure rollup (the cli is powerful but I find it less ergonomic)

touch build-javascript.js

You can then type in the following:

// Require rollup
const rollup = require( 'rollup' );

// Set up your paths
const entries = [ {
  inPath: 'client/scripts/bootstrap.js',
  outPath: 'views/inlines/bootstrap.js'
} ];

let cache;

// Call Rollup on every resource
entries.forEach( entry => {
  rollup.rollup( {
    entry: `src/${entry.inPath}`,
    cache
  } ).then( bundle => {
    cache = bundle;
    bundle.write( {
      format: 'iife',
      dest: `dist/${entry.outPath}`
    } );
  } );
} );

Aaand there you have it! Simple to grasp, easy to configure (through that entries array) and extendable.

For instance, you’ll most likely want to add an uglify step. It doesn’t get any easier than the following:

// Require the plugin
const uglify = require('rollup-uglify-plugin');

// ... as before ...

rollup.rollup( {
    entry: `src/${entry.inPath}`,
    // Add the plugins array in the config object
    plugins: [
       uglify()
    ]
    cache
  } )

// ... as before ...

Don’t forget to npm install rollup-uglify-plugin and you're set!

Hope this helps anyone. Especially if you don’t feel like navigating the task managers waters and simply run an npm script, for instance. Just add this to your package.json

"scripts": {
  "build-js": "node build-javascript.js"
}

and then run npm run build-js

If you’ve found this post useful at all, press the ❤ button! I read each and every comment, so be sure to contribute to the conversation with your thoughts!

Care to leave a comment? Drop down a line on the Twitters