简体   繁体   中英

Webpack babel-loader es2015 presets setting is not working

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']
            }
        }]
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM