I try to make webpack tree-shaking remove unused babel-polyfill
.
index.js
file contains:
import 'babel-polyfill'
const add4 = n => n + 4
const add5 = n => n + 5
add4(6)
console.log('boom', add4(4))
In this file no code require any es2015+ polyfill, so I expected tree-shaking to remove the unused babel-polyfills in the bundled output. It's not the case, and the bundle still contains them (minified).
Here is a git repo with this code.
The webpack config:
const MinifyPlugin = require('babel-minify-webpack-plugin')
module.exports = {
entry: './index.js',
output: {
filename: 'bundle-webpack.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new MinifyPlugin({ mangle: { topLevel: true } }, { comments: false })
]
}
and .babelrc
:
{
"presets": [
[
"env",
{
"targets": {
"browsers": ["chrome >= 50", "iOS >= 10", "ie >= 8"]
},
"useBuiltIns": true,
"modules": false,
"loose": true
}
]
]
}
I tried to replace babel-minify-webpack-plugin
with uglifyjs-webpack-plugin
, but it gave the same result.
How is it possible to make tree-shaking work, and the output not contain any babel-polyfills
which are not used in the original code?
At webpack configuration, optimization/usedExports: true will remove unused code.
Principles behind Tree Shaking: Declare all your imports and exports for each of your modules. The bundler (Webpack, Rollup, etc.) will analyze the dependency tree during your compilation step. Any unused code that can be proved is automatically dropped from your final bundle or tree shaken.
Now Webpack 2+ only marks code unused and doesn't export it inside the module. It pulls everything and leaves unused code for minification libraries. You can use UglifyJS with babel for this.
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).
Now I realize that babel-polyfill modifies the global scope where tree-shaking might have no effects...
This was a stupid question : )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With