Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack 4 and Uglify Plugin (TypeError: Cannot read property 'length' of undefined)

I'm having problems with Webpack 4 on a Linux machine. The build works fine in dev mode, but fail in production. It also seems to be working on a windows machine. I did try do downgrade webpack to an older version and nothing.

Nodejs: v10.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'
    }
}
like image 934
yacine benzmane Avatar asked Jul 09 '18 10:07

yacine benzmane


1 Answers

Setting mode to production in Webpack v4 should do enough optimisations, so there's no need to specifically require the Uglify plugin. Try remove uglifyjs-webpack-plugin and there's also no need for passing the -p flag for the build script.

If you want to customise the Uglify plugin, you can also do so in Webpack's optimization config, see https://webpack.js.org/configuration/optimization/

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

module.exports = {
  //...
  optimization: {
    minimizer: [
      new UglifyJsPlugin({ /* your config */ })
    ]
  }
};

Finally, I have a basic webpack v4 starter boilerplate with all the latest ecosystem on Github, take a look and see if it will help you or not

like image 171
zenoh Avatar answered Nov 14 '22 23:11

zenoh