Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 779
micobg Avatar asked Mar 08 '23 10:03

micobg


1 Answers

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 });
like image 102
nbkhope Avatar answered Apr 24 '23 00:04

nbkhope