micobg
micobg

Reputation: 1342

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)

Upvotes: 4

Views: 2985

Answers (3)

Michelle Norris
Michelle Norris

Reputation: 594

I was using an outdated version of ChromeHeadless due to Puppeteer v1, and updating to v16 (for node 16) removed the "Unexpected token '.'" error.

Upvotes: 0

nbkhope
nbkhope

Reputation: 7474

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 });

Upvotes: 8

Nandu Kalidindi
Nandu Kalidindi

Reputation: 6280

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

Upvotes: 0

Related Questions