我注意到在常规 javascript 应用程序和 Gatsby 应用程序中 Set 类型对象的行为不一致。
在 codesandbox.io 中,创建一个常规的 React 应用程序并将这些行放在开头的某个位置:
const set = new Set(["A", "B", "C"])
const set2 = new Set([...set, "D"])
console.log(set2)
控制台打印:
Set {}
0: "A"
1: "B"
2: "C"
3: "D"
然后,创建一个新的 Gatsby 应用程序并放入相同的代码。控制台将打印:
Set {}
0: Set
0: "A"
1: "B"
2: "C"
1: "D"
为什么这些结果不同,以及如何使 Gatsby 应用程序中的 Set 表现得像一个普通的 Set(使用扩展运算符正确克隆)?
最佳答案
哇,好发现!我喜欢像这样容易重现的问题。
问题源于 Gatsby 在 source code 中使用了 babel ( loose
mode ) .松散模式的 TL;DR 是它可能会生成更快的代码,但作为交换,它与 es6 的兼容性较低。
如果你去Babel repl并打开左侧边栏的es2015-loose
,你会看到你的代码会变成这样:
//original
const set = new Set(['a', 'b', 'c'])
const set2 = new Set([ ...set, 'd'])
//transformed
var set = new Set(['a', 'b', 'c']);
var set2 = new Set([].concat(set, ['d']));
你可以在这里看到问题。 [].concat(new Set(['a']))
不会将 set 转换为数组,因此我们最终得到一组 [Set, 'd']
.
解决这个问题
简单的方法是在您的代码中解决这个问题:
const set = new Set(['a', 'b', 'c'])
const set2 = new Set([ ...Array.from(set), 'd'])
// Set[ 'a', 'b', 'c', 'd' ]
或者你可以为 Gatsby 提供你自己的 babel 配置,通常在根目录下创建一个 .babelrc
:
touch .babelrc
# install new dependencies --
# they're probably already installed,
# but I think it's better to be explicit
yarn add @babel/preset-env @babel/preset-react @babel/plugin-proposal-class-properties babel-plugin-macros @babel/plugin-syntax-dynamic-import @babel/plugin-transform-runtime -D
并复制 gatsby 的默认配置,但关闭 loose
模式:
{
"presets": [
[
"@babel/preset-env",
{
"corejs": 2,
"loose": false,
"modules": false,
"useBuiltIns": "usage",
"targets": "> 0.25%, not dead"
}
],
[
"@babel/preset-react",
{
"useBuiltIns": true,
"pragma": "React.createElement",
"development": true
}
]
],
"plugins": [
[
"@babel/plugin-proposal-class-properties",
{
"loose": true
}
],
"babel-plugin-macros",
"@babel/plugin-syntax-dynamic-import",
[
"@babel/plugin-transform-runtime",
{
"helpers": true,
"regenerator": true
}
]
]
}
关于javascript - 使用扩展运算符克隆集会导致 Gatsby 中的嵌套集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56775730/