Unexpected token { with Webpack 4 and @babel/preset-env

564 Views Asked by At

This is my .babelrc:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}

Here's where the error comes from. \client\src\components\AddBook.js:

const { handleSubmit, pristine, reset, submitting } = this.props;

The error message

   11 |   }
   12 |
 > 13 |   const { handleSubmit, pristine, reset, submitting } = this.props;
      |         ^
   14 |
   15 |   const handleSubmit = (allValues) => {
   16 |     console.log('formData:', allValues);

I thought @babel/preset-env took care of all the latest JavaScript syntax. What does make the code break? The complete repo is on https://github.com/ElAnonimo/booklist

1

There are 1 best solutions below

3
On

Your .babelrc does not explicitly define which browsers/versions it is supposed to transpile code for.

Adjust the following sample .babelrc to your needs:

{ 
  "presets": [
    [ "@babel/preset-env", {
      "targets": {
        "browsers": [ "last 1 version", "ie >= 11" ]
      },
      "@babel/preset-react"
    ]
  ]
}

https://babeljs.io/docs/en/babel-preset-env#targets

Also when using webpack you need to tell babel-loader explicitly to respect .babelrc and where it is located.

loader: 'babel-loader',
options: {
  babelrc: path.join(process.cwd(), './babelrc')
}

, assuming .babelrc is located in your project's root directory.