Webpack babel-loader es2015 presets setting is not working

2.8k views Asked by At

When I build react project with webpack, I got an 'Unexpected token' error

webpack --progress

ERROR in ./src/App.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (13:13)

  11 |     }
  12 | 
> 13 |     onSearch = (e) => {
     |              ^
  14 |         console.log('click');
  15 |     }

I thought my project doesn't transpile es6 codes to es5 because wrong setting of webpack.config.js, but I can't find what's wrong.

webpack.config.js

module.exports = {
    entry: __dirname + "/src/App.js",
    output: {
        path: __dirname + "/public",
        filename: "bundle.js"
    },
    module: {
        rules: [{
            test: /\.js?$/,
            loader: 'babel-loader',
            query: {
                cacheDirectory: true,
                presets: ['react', 'es2015']
            }
        }]
    }
}
1

There are 1 answers

1
Tu Nguyen On BEST ANSWER

Install babel-preset-stage-2 package and try this:

.babelrc

{
  "presets": ["es2015", "react", "stage-2"]
}

webpack.config.js

...
presets: ["es2015", "react", "stage-2"]
...

In the future, we might not use the babel's state presets as this Removing Babel's Stage Presets article said.

However, for now, it worked really well

What's Babel's Stage Presets:

A Babel preset is a shareable list of plugins.

The official Babel Stage presets tracked the TC39 Staging process for new syntax proposals in JavaScript.

Each preset (ex. stage-3, stage-2, etc.) included all the plugins for that particular stage and the ones above it. For example, stage-2 included stage-3, and so on.