使用扩展运算符克隆集会导致 Gatsby 中的嵌套集

Cloning Set using spread operator results in nested set in Gatsby

我注意到在常规 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 对 babel 的使用(source code) in 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, '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
      }
    ]
  ]
}