The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Tree shaking with Webpack 2

Tree shaking with Webpack 2

3:23
The less code you can send to the browser, the better. The concept of tree shaking basically says that if you’re not using some piece of code, then exclude it from the final bundle, even when that piece of code is exported from a module. Because ES6 modules are statically analyzable, Webpack can determine which of your dependencies are used and which are not. In this lesson, see how to take advantage of this awesome feature in Webpack 2.
Watch this lesson now
Avatar
egghead.io

The less code you can send to the browser, the better. The concept of tree shaking basically says that if you’re not using some piece of code, then exclude it from the final bundle, even when that piece of code is exported from a module. Because ES6 modules are statically analyzable, Webpack can determine which of your dependencies are used and which are not. In this lesson, see how to take advantage of this awesome feature in Webpack 2.

Avatar
Peng

I don't understand why it does not remove unused code in my project...

My webpack version is 2.1.0-beta.13.

I define the js like below:

export {a, b, c, d}

function a(){}
function b(){}

And I make sure that function b is never used.
But after webpack build (with uglify plugin enabled), it turns out to be:

function(module,exports,__webpack_require__){"use strict";eval('\n/* harmony export */ __webpack_require__.d(exports, "a", function() { return a; });/* unused harmony export b */\n\nfunction a() {}\nfunction b() {}//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjAwLmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vL3NyYy9wYWdlX2luZGV4L3BhcnRpYWwuanM/MjE5YiJdLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQge2EsIGJ9O1xuXG5mdW5jdGlvbiBhICgpIHtcbn1cbmZ1bmN0aW9uIGIgKCkge1xufVxuXG5cblxuLy8gV0VCUEFDSyBGT09URVIgLy9cbi8vIHNyYy9wYWdlX2luZGV4L3BhcnRpYWwuanMiXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUVBOyIsInNvdXJjZVJvb3QiOiIifQ==')}

You see, function b is still included...

Here is my uglify config:

new webpack.optimize.UglifyJsPlugin({
    compress: {
      dead_code: true,
      unused: true,
    }
  }),
Avatar
Kent C.

Hi Peng,
Are you putting that as your entry file? If so then I don't believe that tree shaking will work because webpack cannot be sure what of your entry file is used and what is not (you could be distributing a library for example which will have external users). That's the only thing I can think of. Other than that, I'm not sure what's going wrong with your case. Sorry!

In reply to Peng
Avatar
Paul

When I try to make my Production Build with the es2015-webpack preset I get the following Error:

ERROR in bundle.js from UglifyJs
Unexpected token: name (React) [./index.jsx:1,7]

That's how my .babelrc looks like:

{
    "presets" : ["es2015-webpack", "react", "stage-1"],
    "plugins" : ["transform-decorators-legacy","transform-class-properties","transform-object-rest-spread","transform-object-assign"]
}

Did I miss something?

Avatar
Kent C.

Hmmm... It looks ok. I would recommend that to debug the problem you comment out the UglifyJs plugin and see what the bundle looks like. Does it run? Make sure you're using the latest webpack 2. It's still in beta, so you have to install it explicitly.

In reply to Paul
Avatar
Paul

Ah ok. I think thats the problem, I use webpack 1.12.15 :)
Thanks.

In reply to Kent C.
Avatar
Mike thompson

What would be different if you had a Typescript project instead of a Babel project?

Avatar
Riva-Dev

the course doesnt starts from scratch, and that made me confused...

Avatar
Kent C.

This course assumes some pre-existing webpack knowledge. If you're entirely new to webpack, you can watch some of the more beginner lessons in this playlist.

In reply to Riva-Dev
Avatar
CTdev

The babel-preset-es2015-webpack preset is not needed anymore since the latest babel release allows you to specify preset options. https://github.com/gajus/babel-preset-es2015-webpack/issues/14#issuecomment-237869435

Avatar
Lingke

Hi there - the video refers to the use of UglifyJS in webpack. I don't see where in webpack.config.js where the UglifyJS plugin is used. Am I missing something?

Also - for newcomers, check out the WIP docs for webpack 2.0: https://gist.github.com/sokra/27b24881210b56bbaff7 - it explains how to use (env) => { ... } as a webpack config versus a straight up object as in 1.x

Avatar
Negin

Seems we need to set the 'module': false for preset es2015. I'm using babel loader and here is my module config
module: {
loaders: [
{
test: /.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
},
{
test: /.scss$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader")
}
]
},

I tried presets: [['es2015', {modules: false}], 'react'] but
I got error on import line for my React component.

How should I set module to false?

In reply to CTdev
Avatar
Kent C.

Give it another shot, I made some updates.

In reply to Negin
Avatar
Negin

Thanks for reply Kent. Did you make some change to the video or a change to the webpack. which one should work

presets: [['es2015', {modules: false}], 'react']
or
presets: ['es2015', 'react', {modules: false}]

?

Thanks

In reply to Kent C.
Avatar
Kent C.

The video hasn't been updated. The correct configuration is:

presets: [['es2015', {modules: false}], 'react']
In reply to Negin
Avatar
apollo

i check out your code from github:
https://github.com/kentcdodds/es6-todomvc/tree/lesson/treeshaking
and run npm start, but it gives me the following error:

webpack result is served from /
content is served from /Users/apollotang/_a/m/me/egghead/Using-Webpack-for-Production-JavaScript-Applications/codes/fork/es6-todomvc-copy2/dist
/Users/apollotang/_a/m/me/egghead/Using-Webpack-for-Production-JavaScript-Applications/codes/fork/es6-todomvc-copy2/node_modules/loader-runner/lib/loadLoader.js:35
            throw new Error("Module '" + loader.path + "' is not a loader (must have normal or pitch function)");
            ^

Error: Module '/Users/apollotang/_a/m/me/egghead/Using-Webpack-for-Production-JavaScript-Applications/codes/fork/es6-todomvc-copy2/node_modules/eslint/lib/api.js' is not a loader (must have normal or pitch function)
Avatar
Kent C.

Hmmm... I'm not sure why you would be getting that error. If I do a fresh clone/install/start, everything works as expected. Here are the commands I ran:

git clone https://github.com/kentcdodds/es6-todomvc.git
cd es6-todomvc
git checkout lesson/treeshaking
npm install
npm start

With that, things run and I see the app come up.

In reply to apollo
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?