最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Babel fails to compile ES6 object cloning with spread operator - Stack Overflow

programmeradmin1浏览0评论

I use grunt-babel to pile 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)

I use grunt-babel to pile 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)

Share Improve this question edited Dec 5, 2017 at 21:07 micobg asked Dec 5, 2017 at 20:45 micobgmicobg 1,3426 gold badges23 silver badges36 bronze badges 3
  • What version of Babel, what babel presets are you using, how are you piling? You left a lot of questions unanswered... – elclanrs Commented Dec 5, 2017 at 20:47
  • Yeah, same issue. I worked around temporarily using Object.assign({}, ) but would like to know a solution. – Nandu Kalidindi Commented Dec 5, 2017 at 20:47
  • babel-core v.6.26.0 and babel-preset-env v.1.6.1 – micobg Commented Dec 5, 2017 at 20:58
Add a ment  | 

3 Answers 3

Reset to default 8

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

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

发布评论

评论列表(0)

  1. 暂无评论