使用Babel压缩Webpack中的ES6代码 [英] Minification for ES6 code in webpack using babel

查看:120
本文介绍了使用Babel压缩Webpack中的ES6代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了Uglifyjs,babelli(babel-minify)之类的选项.似乎没有任何作用.Uglify会引发如下错误:

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

名称应为[au680.bundle.js:147541,22]

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

babelli也不缩小代码.任何人都可以使用webpack 2,babel给出es6缩小的简单示例. 可能是可以正常工作的插件.

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"
    }
  }
}

推荐答案

更新

如果您不担心支持较旧的浏览器,则 webpack v4 +将通过以下方式使代码最小化生产模式下默认设置:

webpack --mode=production

上一个答案

来自 https://github.com/webpack/webpack/issues/2545:

问题在于UglifyJS尚不支持ES6,因此尚无法避免这种转换.您可以通过 mishoo/UglifyJS2#448 跟踪进度.

有很多解决方案;这是一对:

There are many solutions; here are a couple:

首先转换您的ES6代码,然后将其最小化
为了获得最大的兼容性,请使用Babel进行转换,然后使用Babel Minify(以前称为Babili)进行缩小:

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

  1. 安装 babel-loader 或者:

    yarn add babel-loader babel-minify-webpack-plugin --dev
    

  2. 将此添加到webpack.config.js:

  3. 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()
      ]
    };
    

    或者,如果您愿意,可以使用UglifyJS代替Babel Minify:

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

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

  4. 最小化您的ES6代码而无需进行编译
    为了仅与支持您所使用的ES6功能的浏览器兼容,请使用Babel Minify进行缩小而不进行编译:

    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. 安装 babel-minify-webpack-plugin

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

    或者:

    yarn add babel-minify-webpack-plugin --dev
    

  5. 将此添加到webpack.config.js:

  6. Add this to webpack.config.js:

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

  7. Babel Minify的默认设置对我来说很好用,但是您可以在此处查看更多可以自定义的选项: https://github.com/webpack-contrib/babel-minify-webpack-plugin

    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

    这篇关于使用Babel压缩Webpack中的ES6代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆