Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tree shaking not working - webpack 4 and uglifyjs-webpack-plugin

I have tried adding UglifyJSPlugin to a webpack 4 project, in accordance with the webpack docs, and I'm still seeing dead code and even comments in my bundle which leads me to think that my uglify plugin config isn't being used.

Link to project

The docs state that "in order to take advantage of tree shaking, you must...
- Use ES2015 module syntax (i.e. import and export). done
- Add a "sideEffects" entry to your project's package.json file. done .
- Include a minifier that supports dead code removal (e.g. the UglifyJSPlugin)." done

Still, the unused/unimported leftpad function and comments are being included in my bundle.

All of the config can be seen here. Based on the results I'm seeing, I suspect that this is related to the uglify settings in my webpack config.

To reproduce, pull the repo and run yarn build

like image 326
ItsGeorge Avatar asked Mar 21 '18 01:03

ItsGeorge


People also ask

Why is webpack not tree shaking?

In webpack, tree shaking works with both ECMAScript modules (ESM) and CommonJS, but it does not work with Asynchronous Module Definition (AMD) or Universal Module Definition (UMD).

How do I turn on a tree shaking webpack?

Add a "sideEffects" property to your project's package. json file. Use the production mode configuration option to enable various optimizations including minification and tree shaking.

What is UglifyJS webpack plugin?

Allows you to override default minify function. By default plugin uses uglify-js package. Useful for using and testing unpublished versions or forks. ⚠️ Always use require inside minify function when parallel option enabled. webpack.config.js.

How webpack detect the dead code that can help in tree shaking?

Tools like webpack will detect dead code and mark it as “unused module” but it won't remove the code. Webpack relies on minifiers to cleanup dead code, one of them is UglifyJS plugin, which will eliminate the dead code from the bundle. It only works with import and export . It won't work with CommonJS require syntax.


1 Answers

tree shaking is only enabled in production mode

See https://github.com/webpack/webpack/issues/6992#issuecomment-379665061

This explanation is misleading, because not only UglifyJsPlugin but also a bunch of plugins are needed to make it work as explained here.

I have not tried enabling all the plugins to see if it works. I have tried "--optimize-minimize" option but it doesn't work.

like image 157
apptaro Avatar answered Oct 13 '22 21:10

apptaro