Minification for ES6 code in webpack using babel

本秂侑毒 提交于 2019-12-04 11:58:50

问题


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]

babelli does not minifies the code either.Can any one give simple example of es6 minification making use of webpack 2, babel. May be a plugin that do the work cleanly.

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var AppCachePlugin = require('appcache-webpack-plugin');

var appConfig= require('./config.js');
console.log("appConfig is ->>>",appConfig);
var appPort = appConfig.APP_PORT;//Port on which the application is running

process.noDeprecation = true;
var ASSET_PATH = '/'
module.exports = function(options) {
  var entry, jsLoaders, plugins, cssLoaders, devtool;
  console.log('options webconfig-->', options, 'directory name', __dirname);

  // If production is true
  if (options.prod) {
    console.log('production minification');
    // Entry
    entry = {
       veris:path.resolve(__dirname,'./VerisInstrument/js/VerisApp.js'),
       au680 : path.resolve(__dirname,'./Au680Instrument/js/au680App.js'),
	   commondashboard:path.resolve(__dirname,'./CommonDashboard/js/CommonDashboardApp.js'),
       groups:path.resolve(__dirname,'./Groups/js/GroupsApp.js'),
       homepage : path.resolve(__dirname,'./HomePage/js/HomePageApp.js'),
       infohealthcheck : path.resolve(__dirname,'./Common/js/infohealthcheckapp.js')
      
    };

   
    // Plugins
    plugins = [// Plugins for Webpack
    new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify('production')
    }
   }),
  //   new webpack.optimize.UglifyJsPlugin({minimize: true,comments : false,compress: {
  //   // remove warnings
  //   warnings: false,

  //   // Drop console statements
  //   drop_console: true
  // }})

    
      // new es3MemberExpressionLiterals(),
      //
      
    ];

  // If app is in development
  } else {
    devtool = 'source-map';
    // Entry
    // entry = [
    //   "webpack-dev-server/client?http://0.0.0.0:" + appPort, // Needed for hot reloading
    //   "webpack/hot/only-dev-server", // See above
    //   //path.resolve(__dirname,'./app') // Start with js/app.js...
    //   path.resolve(__dirname,'./VerisInstrument/js/VerisApp')
    // ];
  //   require("babel-core").transform("code", {
  //   plugins: ["transform-object-rest-spread"]
  // });
    entry = {
      main: [
        "webpack-dev-server/client?http://0.0.0.0:" + appPort, // Needed for hot reloading
        "webpack/hot/only-dev-server" // See above
      ],
      //path.resolve(__dirname,'./js/app') // Start with js/app.js...
     veris : path.resolve(__dirname,'./VerisInstrument/js/VerisApp'),
      au680 : path.resolve(__dirname,'./Au680Instrument/js/au680App.js'),
	  commondashboard:path.resolve(__dirname,'./CommonDashboard/js/CommonDashboardApp.js'),
      groups:path.resolve(__dirname,'./Groups/js/GroupsApp.js'),
      homepage : path.resolve(__dirname,'./HomePage/js/HomePageApp.js'),
      infohealthcheck : path.resolve(__dirname,'./Common/js/infohealthcheckapp.js')
      
    };
    
    // Only plugin is the hot module replacement plugin
    plugins = [
     new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify('development'),
      }
     }),
     new webpack.HotModuleReplacementPlugin()// Make hot loading work,
    ]
  }

  return {
    devtool: devtool,
    entry: entry,
    // output: { // Compile into js/build.js
    //   path: path.resolve(__dirname, 'build'),
    //   filename: "js/bundle.js",
    //   publicPath : '/'
    // },
    output: { // Compile into js/build.js
      path: path.resolve(__dirname, 'build'),
      filename: '[name].bundle.js',
      publicPath : ASSET_PATH
    },
    module: {
      rules: [
      {
          test: /\.js$/, // Transform all .js files required somewhere within an entry point...
          loader: 'babel-loader', // ...with the specified loaders...
          exclude: /node_modules/,
          options: {
          presets: ['es2015','react','stage-2','env'],
          plugins: [require('babel-plugin-transform-object-rest-spread'),require('babel-plugin-transform-es2015-destructuring'),require('babel-plugin-transform-es2015-parameters')]
        }
          // query : {
          //   presets : ['es2015','react','stage-2','env']
          // }

        }
        , {
          test:   /\.css$/, // Transform all .css files required somewhere within an entry point...
          use : [
            {
              loader : 'style-loader'
            },
            {
              loader : 'css-loader'
            },
            {
              loader : 'postcss-loader'
            },
            {
              loader: 'sass-loader'
            }
          ] // ...with PostCSS
        }, {
          test: /\.jpe?g$|\.gif$|\.png$/i,
          loader: "url-loader?limit=100000"
        },
        { test: /\.(woff|woff2|eot|ttf|svg)$/,
         loader: 'url-loader?limit=100000' }
      ]
    },
    plugins: plugins,
    target: "web", // Make web variables accessible to webpack, e.g. window
    stats: false, // Don't show stats in the console
    node: {
      fs: "empty"
    }
  }
}

回答1:


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




回答2:


Following is my webpack configurations file. I am using webpack 2.3.1 with dynamic routing of react-router. Hope it helps you.

var path = require('path');
var webpack = require('webpack');
var package=require('./package.json');
var config = require('./config');
var ManifestPlugin = require('webpack-manifest-plugin');


const ExtractTextPlugin = require('extract-text-webpack-plugin');
var getPlugins = function(){
  var pluginsList = [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: Infinity,
      filename: 'vendor.bundle_[hash].js'
    }),

    new webpack.DefinePlugin({
      "process.env": {
         NODE_ENV: JSON.stringify("production")
       }
    }),
    new webpack.NamedModulesPlugin(),
    new ManifestPlugin({
      fileName: 'build-manifest.json'
    })
  ];
    pluginsList.push(new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }));
    pluginsList.push(new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      output: {
        comments: false
      },
      sourceMap: false,
      minimize: true
    }));
  return pluginsList;
}



module.exports = {
  cache: true,
  output: {
    path:path.join(__dirname, "dist/js"),
    filename: "[name]_[hash].js",
    chunkFilename:"[name]_[hash].js",
    publicPath:config.envConfig.JS_ASSETS_PATH
  },
  devServer: {
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    port: 8080
  },

  entry: {
    index: [
      package.paths.app
    ],
    vendor: [
      'react', 'react-dom','phrontend',
      'react-ga'
    ]
  },
  plugins: getPlugins(),
  target: 'web',

  module: {
    rules: [
      {
        test: /.jsx?$/,
        exclude: /node_modules/,
        use: [{
          loader: 'babel-loader',
        }]
      }
    ]
  },
};


来源:https://stackoverflow.com/questions/43870615/minification-for-es6-code-in-webpack-using-babel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!