正确使用方法可以最小化webpack.config.js中的javascript

时间:2018-03-01 01:11:22

标签: javascript npm webpack

我正在关注webpack的教程,但似乎该教程正在使用较早版本的webpack。我尝试最小化.js文件,但每次运行npm run webpack时,我都会在控制台中收到此错误消息:

  

webpack.optimize.UglifyJsPlugin已被删除,请使用   相反,config.optimization.minimize。

如何使用config.optimization.minimize?我已经谷歌搜索了一段时间但没有成功......我需要在我的webpack.config.js中更改什么?

这是我的webpack.config.js

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractCSS = new ExtractTextPlugin('allstyles.css');

module.exports = {
  entry: './wwwroot/source/app.js',
  output: {
    path: path.resolve(__dirname, 'wwwroot/dist'),
    filename: 'bundle.js'
  },
  plugins: [
    extractCSS,
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery',
      Popper: ['popper.js', 'default']
    }),
    new webpack.optimize.UglifyJsPlugin()
  ],
  module: {
    rules: [
      {test: /\.css$/, use: extractCSS.extract(['css-loader?minimize'])},
      {test: /\.js$/,//      
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      }
    ]
  }
};

package.json

{
  "name": "WebpackBlogExample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "wbp": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.3",
    "babel-preset-env": "^1.6.1",
    "bootstrap": "^4.0.0-beta.2",
    "css-loader": "^0.28.10",
    "extract-text-webpack-plugin": "^3.0.2",
    "jquery": "^3.3.1",
    "popper.js": "^1.12.9",
    "style-loader": "^0.20.2",
    "uglifyjs-webpack-plugin": "^1.2.2",
    "webpack": "^4.0.1",
    "webpack-cli": "^2.0.9"
  },
  "dependencies": {}
}

2 个答案:

答案 0 :(得分:3)

https://medium.com/webpack/webpack-4-mode-and-optimization-5423a6bc597a

如果您查看网址,它会解释所有优化选项。

默认情况下,在开发模式下,webpack 4不会最小化js,这是为了加快开发速度。一旦你将模式切换到生产或在运行webpack时使用-p,它将自动最小化你的JS,不再需要在webpack 4中设置uglifyjs。

答案 1 :(得分:0)

Webpack 4.X并缩小JS

<强> UglifyJSPlugin:

const UglifyJSPlugin = require('uglifyjs-webpack-plugin')

...

optimization: {
  minimizer: [
    new UglifyJSPlugin({
      uglifyOptions: { ... }
    })
  ]
}

其他选择:

请注意,虽然UglifyJSPlugin是开始缩小的好地方,但还有其他选择。以下是一些更受欢迎的:

[BabelMinifyWebpackPlugin][1]
[ClosureCompilerPlugin][1]

如果您决定尝试另一种选择,请确保您的新选择也删除了死树代码中描述的死代码。

来源:https://webpack.js.org/guides/production/

看看: https://stackoverflow.com/a/49767690/6200607