Minification for ES6 code in webpack using babel

后端 未结 2 710
难免孤独
难免孤独 2021-02-06 03:18

I have tried options such as Uglifyjs,babelli (babel-minify ).nothing seems to be working.Uglify throws some error like this:

Name expected [au680.bundle.js:147541,22]

2条回答
  •  没有蜡笔的小新
    2021-02-06 03:49

    Update

    If you aren't worried about supporting older browsers, webpack v4+ will minify your code by default in production mode:

    webpack --mode=production
    

    Previous answer

    From https://github.com/webpack/webpack/issues/2545:

    The problem is that UglifyJS doesn't support ES6 yet so it's not possible to avoid that transformation yet. You can follow the progress at mishoo/UglifyJS2#448 .

    There are many solutions; here are a couple:

    Transpile your ES6 code first, then minify it
    For maximum compatibility, transpile using Babel and then minify with Babel Minify (formerly Babili):

    1. Install babel-loader and babel-minify-webpack-plugin

      npm install babel-loader babel-minify-webpack-plugin --save-dev
      

      Or:

      yarn add babel-loader babel-minify-webpack-plugin --dev
      
    2. Add this to webpack.config.js:

      const MinifyPlugin = require('babel-minify-webpack-plugin');
      
      module.exports = {
        // ...
        module: {
          rules: [
            {
              test: /\.js$/,
              use: {
                loader: 'babel-loader',
                options: {
                  presets: ['env']
                }
              }
            }
          ]
        },
        plugins: [
          new MinifyPlugin()
        ]
      };
      

      Or if you prefer you can use UglifyJS instead of Babel Minify:

      const MinifyPlugin = require('uglifyjs-webpack-plugin');
      

    Minify your ES6 code without transpiling
    For compatibility only with browsers that support the ES6 features you're using, minify using Babel Minify without transpiling:

    1. Install babel-minify-webpack-plugin

      npm install babel-minify-webpack-plugin --save-dev
      

      Or:

      yarn add babel-minify-webpack-plugin --dev
      
    2. Add this to webpack.config.js:

      const MinifyPlugin = require('babel-minify-webpack-plugin');
      
      module.exports = {
        // ...
        plugins: [
          new MinifyPlugin()
        ]
      };
      

    The default settings for Babel Minify worked fine for me but you can see here for more options you can customize: https://github.com/webpack-contrib/babel-minify-webpack-plugin

提交回复
热议问题