简体   繁体   中英

I cannot use the rest operator in webpack with Babel

I'm using webpack and React for my app, and for some reason webpack is not liking var {id, ...data} = pulse; .

Error:

ERROR in ./src/main.js
Module build failed: SyntaxError: Unexpected token (122:13)

  120 |   },
  121 |   editPulse: function(pulse) {
> 122 |     var {id, ...data} = pulse;
      |              ^
  123 |     console.log('Calling editPulse API: ');
  124 |     console.log(id, data);
  125 |     console.log(JSON.stringify(data));

My webpack.config.js looks like this:

module.exports = {
  ...snip...
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  }
};

And through npm, my package.json is:

{
  ...snip...
  "devDependencies": {
    "babel-core": "^6.16.0",
    "babel-loader": "^6.2.5",
    "babel-preset-es2015": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "css-loader": "^0.25.0",
    "style-loader": "^0.13.1",
    "webpack": "^1.13.2"
  },
  "dependencies": {
    "babelify": "^7.3.0",
    "jquery": "^3.1.1",
    "react": "^15.3.2",
    "react-addons-update": "^15.3.2",
    "react-bootstrap": "^0.30.3",
    "react-dom": "^15.3.2"
  }
}

Like Jonathan Lonowski said above, you'll need to npm install one of the babel-preset-stage-(0-3 here) in order to use the Rest notation/Es2015 object spread notation.

Don't forget to add the preset to your webpack.config.js file too. So if you installed the stage-2 babel preset your config file should have babel-preset-stage-2 as an additional entry under: module: loaders: query

From @Jonathan Lonowski's comment , I installed the babel-preset-stage-3 to add support to use the rest operator on Objects.

npm install babel-preset-stage-3 --save-dev

Then update the webpack.config.js to include that preset:

presets: ['react', 'es2015', 'stage-3']

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