简体   繁体   中英

Babel fails to compile ES6 object cloning with spread operator

I use grunt-babel to compile my ES6 code. But it returns Warning: dist/app.js: Unexpected token (321:9) Use --force to continue. when I try to use {...obj} to copy and extend object. Following code is working perfect in console of Chrome v61 but Babel doesn't like it. What is the problem?

let a = { a: 12 };
let b = { ...a, b: 15 };

I am using env preset. ( babel-core v.6.26.0 and babel-preset-env v.1.6.1 )

The spread property for objects is not part of ES6. Currently, as of Dec 2017, it is part of the stage 3 proposal for ECMAScript. You can have a look at the proposal here .

You need a babel preset that includes features not yet officially in the language. The babel-preset-env does not include those features.

To solve your problem, you could use something like babel-preset-stage-3 and add "stage-3" to the list of presets in your .babelrc .

Side note:

An alternative to the spread syntax for objects in ES6 is to use Object.assign

let b = Object.assign({}, a, { b: 15 });

You probably would want to add these plugins to your .babelrc . This Github issue has a lot of solutions unexpected token (rest spread operator) . I am trying these out now.

{
  "presets": ["react", "es2015"],
  "plugins": ["transform-es2015-destructuring", "transform-object-rest-spread"]
}

npm install --save-dev babel-plugin-transform-es2015-destructuring

npm install --save-dev babel-plugin-transform-object-rest-spread

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