我在Linux机器上使用Webpack 4时遇到了问题。构建在开发模式下运行良好,但在生产模式下失败。它似乎也在Windows机器上工作。我确实尝试将 webpack 降级到旧版本,但什么都没有。
Nodejs: 10.2.1 版
*TypeError: Cannot read property 'length' of undefined* at node_modules/uglifyjs-webpack-plugin/dist/uglify/index.js:59
this.workers = workers === true ? _os2.default.cpus().length - 1 : Math.min(Number(workers) || 0, _os2.default.cpus().length - 1);
packge.json
{
"name": "webpack-demo",
"version": "1.0.0",
"license": "MIT",
"scripts": {
"build": "webpack -p"
},
"devDependencies": {},
"dependencies": {
"@types/node": "^10.5.1",
"css-loader": "^0.28.11",
"global": "^4.3.2",
"node-sass": "^4.9.1",
"npm": "^6.1.0",
"sass-loader": "^7.0.3",
"style-loader": "^0.21.0",
"ts-loader": "^4.4.2",
"typescript": "^2.9.2",
"uglifyjs-webpack-plugin": "1.0.0-beta.2",
"webpack": "^4.15.1",
"webpack-cli": "^3.0.8"
}
}
webpack.config.js
const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
var webpack = require('webpack');
module.exports = {
entry: './src/index.ts',
devtool: 'source-map',
mode: 'production',
module: {
rules: [{
test: /.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
exclude: /node_modules/
}
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js','.css','.scss']
},
plugins: [
new UglifyJsPlugin()
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.js'
}
}
在Webpack v4 中将mode
设置为production
应该会进行足够的优化,因此无需特别要求 Uglify 插件。尝试删除uglifyjs-webpack-plugin
,也无需传递build
脚本的-p
标志。
如果你想自定义 Uglify 插件,你也可以在 Webpack 的optimization
配置中这样做,请参阅 https://webpack.js.org/configuration/optimization/
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
//...
optimization: {
minimizer: [
new UglifyJsPlugin({ /* your config */ })
]
}
};
最后,我有一个基本的 webpack v4 入门样板,其中包含 Github 上所有最新的生态系统,看看它是否会对您有所帮助