Webpack/Babel/React - “Uncaught SyntaxError: Unexp

2019-07-18 02:55发布

问题:

I have a webpack-dev-server running that compiles and serves some Babel/React code. I have gotten as far as to have it serve the compiled client.js over localhost:3001.

But when I try to include the script in my HTML, I get the following error in Chrome's developer console:

routerWarning.js:19 Uncaught SyntaxError: Unexpected token :

That line belongs to react-router and contains the following code:

process.env.NODE_ENV !== 'production' ? _warning2['default'].apply(undefined, [falseToWarn, message].concat(args)) : undefined;

First, I don't see how that line of code would cause a syntax error. And second, I don't understand how it got in, because this looks like a piece of compiled (babelified) code to me. And finally, I don't know how to fix it! :(

Any help would be greatly appreciated.

回答1:

I was using webpack's DefinePlugin to set process.env.BABEL_ENV like this:

new DefinePlugin({
  'process.env': {
    BABEL_ENV: JSON.stringify('client')
  }
});

This resulted in webpack replacing all instances of process.env in the code with {"BABEL_ENV":"client"}. The SyntaxError was caused in this part, not in the ternary expression.

I fixed it by setting process.env.BABEL_ENV like this:

new DefinePlugin({
  'process.env.BABEL_ENV': JSON.stringify('client')
});