Tree shaking is an important concept which is gaining a lot of coverage in the past few months.It is basically removing unused code from your bundle and thus providing a highly optmized bundle.It essentially reduces the size of the payload which could be a performance boost as well as makes it easier to maintain.

Tree shaking is one of the most anticipated features of Webpack 2.It supports native ES6 modules without converting them to CommonJS format.This is a big plus as tree shaking is not possible with Common JS modules.

What is the process like ?

Single bundle file :Webpack2 first creates a single bundle file of all the ES6 modules in your code and if a export is not imported anywhere it is removed.

Minification: Next the bundle is minified and all the dead code is removed.As a result of the first step, dead code elimination can remove the unused exports.

Configuration

Webpack2 can parse and understand all of ES6 and only tree-shakes if it detects an ES6 module. However, only imports and exports are transpiled to ES5. If you want all of the bundle to be in ES5, you need a transpiler for the remaining parts of ES6.

First step is to install webpack2

npm install --save webpack@2.0.1-beta

Next install es2015-native-modules Babel preset for the transpiling part

npm install --save es2015-native-module

Add the plugin to .babelrc file

//.babelrc
{
presets: ["es2015-native-modules"]
}

Add the optmize-minimize flag to the build script for the 2 step process we talked about before

//package.json
"scripts" : {
"build" : "webpack-optimize-minimize"
}

Lets write a greetings library which has different types of greetings.

//greetings.js
export function sayHello(){
return "Hello there";
}
export function sayHi() {
return 'Hi there';
}

lets import this in our index.js.We will only import sayHi() for our project.

//index.js
import { sayHi } from './greetings.js';
 let elem = document.getElementById('greeting');

elem.innerHTML = '${(sayHi())};

Next lets build the code.

npm run build

Below is the bundle after we build the code.

function (t, n, r) {
function e() {
return "Hi there"
}

n.sayHi = e
}

Success !! The function sayHello() is not a part of the bundle as we did not import it and it was removed as part of dead code elimination.

I see tree shaking to be of a lot of value when we import huge libraries like lodash,jquery and end up using only a few functions and bloat up our bundle for no reason.

I am excited to see how this concept evolves and becomes a part of the central ecosystem with Webpack being a popular choice amongst a lot of developers.

Resources

  1. Webpack2 : https://webpack.github.io/docs/roadmap.html
  2. Babel : https://babeljs.io/
Show your support

Clapping shows how much you appreciated Sonia Ramnani’s story.