【问题标题】:Babel incorrect transformation of spreadBabel 不正确的传播变换
【发布时间】:2022-02-08 00:21:45
【问题描述】:

Babel 错误地转换/转译以下代码

const arr = [...new Set([1, 2, 3, 1])]

进入

var arr = [].concat(new Set([1, 2, 3, 1]))

第一个返回一个数字列表,而另一个返回一个集合列表

这是一个 Babel 错误吗?

使用@babel/plugin-transform-spread@7.14.6@babel/plugin-transform-destructuring@7.14.7

【问题讨论】:

  • 你是如何配置 Babel 的?你可以在这里试试它的作用:babeljs.io/repl
  • 你使用的是什么版本的 Babel?您正在使用哪些选项(.babelrc 或类似选项)?您非常不太可能在 Babel 中发现这样一个基本错误,但显然这是可能的。更有可能的是,您有一个设置告诉 Babel 放宽其正确性规则以简化输出。
  • 你使用的是什么版本的 Babel(不是插件)?再说一遍,什么配置?

标签: javascript node.js arrays babeljs transpiler


【解决方案1】:

这似乎与babel/babel#9108 Correctly transform spreads to use proper concat method 相关,后者已合并到v7.2.2

正如 PR 中 smashercosmo’s comment 中提到的……

此 PR 的一个坏处是,在此之前,如果有人试图在 loose 模式下传播 Set,则会引发明显错误,但现在他会得到 [Set()] 的错误输出,这将更难发现.

我认为这正是您在这里看到的。 ? 可能是因为您的 Babel 配置将 loose 设置为 true,但我不确定。

一个潜在的解决方法是使用Array.from

const myArrayWithDupes = ['a', 'b', 'c', 'a'];

console.log([...new Set(myArrayWithDupes)]); // your original line
console.log([].concat(new Set(myArrayWithDupes))); // incorrect when `loose` is set to `true`
console.log(Array.from(new Set(myArrayWithDupes))); // a potential workaround

【讨论】:

  • 你可能是在正确的一般轨道上,但just setting loose doesn't cause this
  • 谢谢@rishabh,看来你已经帮我缩小了范围
  • @T.J.Crowder 嗯,看起来你是对的。我已更新我的答案,只包含解决方法。
猜你喜欢
  • 1970-01-01
  • 2019-12-18
  • 2018-08-08
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多