How to get terser webpack plugin works properly

2020-07-30 05:18发布

问题:

I am trying to understand how to get terser webpack plugin to work in the most simple possible case.

This is my code:

src/math.js, exports 2 functions.

export const double = (x) =>
  x + x;

export const triple = (x) =>
  x + x + x;

scr/index.js, imports only double function.

import { double } from './math.js';
console.log(double(10));

I understood from webpack documentation that I must use ModuleConcatenationPlugin if I want activate tree shaking.

This is my webpack config:

webpack/index.js

const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  mode: 'none',
  module: {
    rules: [
        {
            test: /\.js$/,
            loader: 'babel-loader',
            options: {
                presets: [
                    ['@babel/preset-env', {
                        modules: false
                    }]
                ],
                babelrc: false
            }
        }
    ]
  },
  plugins: [
      new webpack.optimize.ModuleConcatenationPlugin()
  ],
  optimization: {
      minimizer: [new TerserPlugin({})],
  }
};

I don't understand what I missed in my webpack config. The webpack output is without minification or tree shaking...


node: "v10.10.0"

webpack: "^4.28.1"

webpack-cli: "^3.2.1"

@babel/core: "^7.2.2"

@babel/preset-env: "^7.1.5"

babel-loader: "^8.0.5"

terser-webpack-plugin: "^1.2.1"

回答1:

Seeing that you have mode set to none, optimization.minimize is set to false, so your custom instance of Terser is never instantiated.

Add minimize: true to the optimization object and it should work.