【问题标题】:Minification for ES6 code in webpack using babel使用 babel 缩小 webpack 中的 ES6 代码
【发布时间】:2017-05-09 13:03:14
【问题描述】:

我已经尝试过诸如 Uglifyjs,babelli (babel-minify) 之类的选项。似乎没有任何效果。Uglify 会抛出类似这样的错误:

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

babelli 也不会缩小代码。任何人都可以给出使用 webpack 2,babel 进行 es6 缩小的简单示例。 可能是一个干净地完成工作的插件。

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

【问题讨论】:

  • 你试过UglifyJsPlugin吗?你确定你的代码没有错误吗?
  • 尝试在 au680.bundle.js 中使用 UglifyJsPlugin 错误时出现以下错误,来自 UglifyJs Name expected [au680.bundle.js:147540,22] webpack:编译失败。
  • 应用程序运行但我看不到任何缩小发生并且在 CLI 中也看到错误

标签: webpack babeljs production-environment bundling-and-minification


【解决方案1】:

更新

如果您不担心支持旧版浏览器,webpack v4+ will minify your code by default in production mode:

webpack --mode=production

上一个答案

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

问题是 UglifyJS 还不支持 ES6,所以还不能避免这种转换。您可以在mishoo/UglifyJS2#448 关注进度。

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

先转译你的 ES6 代码,然后再缩小它
为了获得最大的兼容性,请使用 Babel 进行编译,然后使用 Babel Minify(以前的 Babili)进行缩小:

  1. 安装babel-loaderbabel-minify-webpack-plugin

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

    或者:

    yarn add babel-loader babel-minify-webpack-plugin --dev
    
  2. 将此添加到 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:

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

无需转译即可缩小 ES6 代码
为了仅与支持您正在使用的 ES6 功能的浏览器兼容,请使用 Babel Minify 进行缩小而不进行转译:

  1. 安装babel-minify-webpack-plugin

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

    或者:

    yarn add babel-minify-webpack-plugin --dev
    
  2. 将此添加到 webpack.config.js:

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

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

【讨论】:

  • 那么对于第二种方法,“在不转译的情况下缩小 ES6 代码”,你知道如何将现有的 babel 选项放入其中吗?比如变换类属性、传播对象等。
  • 谢谢。虽然我正在创建一个类似 lib 的 create-react-app。所以我必须传入 Babel 选项对象,而不是依赖 .babelrc 文件。
  • @garyx 好的,我想我现在更好地理解了这个问题。问题是第二种方法跳过了转译过程(这就是 Babel 所做的),所以给它提供 Babel 选项对我来说没有任何意义。如果你想让 Babel 运行,我认为第一种方法是你需要的。但是,您可以将 babel-minify (Babili) 与第一种方法一起使用。我会更新我的答案以反映这一点。
【解决方案2】:

以下是我的 webpack 配置文件。我正在使用带有 react-router 动态路由的 webpack 2.3.1。希望对你有帮助。

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',
        }]
      }
    ]
  },
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    相关资源
    最近更新 更多