0

I am getting an error code that is auto-generated when I use webpack and babel in a NodeJs React application:

Uncaught ReferenceError: Invalid left-hand side in assignment

Here is the offending line in the code auto-generated by babel/webpack:

"development" = 'development'; // bundle.js line 17933

If I manually delete the above line from the auto-generated code then the error goes away. But that is not a good solution for obvious reasons.

I'm using webpack 4, as shown in this excerpt from package.json:

"babel-loader": "^7.1.4",
"babel-preset-stage-0": "^6.24.1",
"webpack": "^4.1.1",
"webpack-cli": "^2.0.12"

Here is my webpack.config.js:

module.exports = {
    entry: './source/main.js',
    output: {
        path: __dirname,
        filename: 'public/javascripts/bundle.js'
    },
    devtool: "inline-source-map",
    module: {
        rules: [
            {
                test: /.js?$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: ['react', 'stage-0']
                    }
                }
            }
        ]
    }
};

I build bundle.js like this:

node_modules/.bin/webpack --mode development

The error goes away if I keep everything the same but use webpack 3.11.0 and uninstall webpack-cli and build bundle.js like this:

node_modules/.bin/webpack

NOTE: The latest webpack 3.X versions support the webpack 4.X syntax shown in my webpack.config.js.

Details:

$ node --version
v9.8.0
$ npm --version
5.7.1
ccalvert
  • 3,816
  • 1
  • 23
  • 22
  • Your configuration seems ok. I think my [webpack-demo](https://github.com/carloluis/webpack-demo) project can help you with **webpack-4** and **react**. Try to build/run locally and let me know if it works for you. – Carloluis Mar 20 '18 at 02:55

2 Answers2

0

What I would do is to export a function out of the webpack.config.js module.

When you export a function, the function will be invoked with 2 arguments: an environment as the first parameter (which you can ignore) and an options map as the second parameter.

You can use this in order to get the --mode passed as options to Webpack CLI, and use it to define process.env.NODE_ENV via DefinePlugin. This might be what babel is looking for.

Something like this:

const { DefinePlugin } = require('webpack');
...

module.exports = (env, options) => {
    ...

    plugins: [
        new DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(options.mode)
        })
    ]
};
Fernando Espinosa
  • 4,625
  • 1
  • 30
  • 37
0

You probably have this line (or similar) somewhere in your code:

process.env.NODE_ENV = 'development';

In build time, Webpack's DefinePlugin will replace process.env.NODE_ENV with the actual value (development in your case) and the result will be: "development" = 'development'; which will throw an error.

yairhaimo
  • 345
  • 2
  • 10