Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Webpack tree-shaking remove unused babel-polyfills?

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?

like image 874
François Romain Avatar asked Nov 16 '17 10:11

François Romain


People also ask

Does webpack remove unused code?

At webpack configuration, optimization/usedExports: true will remove unused code.

How does tree shake work in webpack?

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.

Does webpack include unused imports?

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.

Does webpack use 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).


1 Answers

Now I realize that babel-polyfill modifies the global scope where tree-shaking might have no effects...

This was a stupid question : )

like image 157
François Romain Avatar answered Oct 02 '22 12:10

François Romain