[英]Babel fails to compile ES6 object cloning with spread operator
I use grunt-babel to compile my ES6 code. 我使用grunt-babel编译我的ES6代码。 But it returns
Warning: dist/app.js: Unexpected token (321:9) Use --force to continue.
但它返回
Warning: dist/app.js: Unexpected token (321:9) Use --force to continue.
when I try to use {...obj}
to copy and extend object. 当我尝试使用
{...obj}
复制和扩展对象时。 Following code is working perfect in console of Chrome v61 but Babel doesn't like it. 以下代码在Chrome v61的控制台中运行完美,但是Babel不喜欢它。 What is the problem?
问题是什么?
let a = { a: 12 };
let b = { ...a, b: 15 };
I am using env preset. 我使用的ENV预设。 ( babel-core v.6.26.0 and babel-preset-env v.1.6.1 )
( babel-core v.6.26.0和babel-preset-env v.1.6.1 )
The spread property for objects is not part of ES6. 对象的传播属性不是ES6的一部分。 Currently, as of Dec 2017, it is part of the stage 3 proposal for ECMAScript.
目前,截至2017年12月,它是ECMAScript第三阶段提案的一部分。 You can have a look at the proposal here .
您可以在这里查看提案 。
You need a babel preset that includes features not yet officially in the language. 您需要一个babel预设,其中包括尚未正式使用该语言的功能。 The
babel-preset-env
does not include those features. babel-preset-env
不包含这些功能。
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
. 为了解决您的问题,您可以使用babel-preset-stage-3之类的东西 ,并将“ stage-3”添加到
.babelrc
中的预设列表中。
Side note: 边注:
An alternative to the spread syntax for objects in ES6 is to use Object.assign ES6中对象的传播语法的替代方法是使用Object.assign
let b = Object.assign({}, a, { b: 15 });
You probably would want to add these plugins to your .babelrc
. 您可能希望将这些插件添加到
.babelrc
。 This Github issue has a lot of solutions unexpected token (rest spread operator) . 这个Github问题有很多解决方案意外的令牌(剩余散布算子) 。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.