3

我正在尝试运行 Gatsby 网站,但是当我这样做时npm run develop,我收到了这个错误:

> gatsby develop

 ERROR #10123  CONFIG

We encountered an error while trying to load your site's gatsby-config. Please fix the error x try again.



  Error: D:\Coding\web-blog\src\infra\feed.js:28
  description: post.intro ?? post.description,
                           ^

代码:

const item = {
                title: sanitizeTitle(post.title),
                description: post.intro ?? post.description,
                url: `${site.siteMetadata.siteUrl}/${post.slug}`,
                guid: `${site.siteMetadata.siteUrl}/${post.slug}`,
                categories: post.tags,
                author: site.siteMetadata.author,
                date: post.date,
            }

什么是JavaScript 中的??运算符?它是一种新的语言功能吗?

4

3 回答 3

4

nullish 合并运算符 ( ??) 它是 ECMAScript 2020 中的一项功能(请参阅 TC39 提案)。您可以通过修改 babel 配置或安装gatsby-plugin-nullish-coalescing-operator插件来添加它。

如果您选择第一个版本,.babelrc请在项目的根目录中添加 a 并使用以下内容填充它:

{
  "plugins": [
    ["@babel/plugin-proposal-nullish-coalescing-operator"]
  ],
  "presets": [
    [
      "babel-preset-gatsby",
      {
        "targets": {
          "browsers": [">0.25%", "not dead"]
        }
      }
    ]
  ]
}

注意:您需要安装@babel/plugin-proposal-nullish-coalescing-operator依赖项。

Javascript 中的这个运算符是什么?

如果 left 是or , nullish 合并运算符 ( ??) 使用正确的值。OR 运算符 ( ) 之间的主要区别在于假值,在,或值中使用时可能会导致一些错误(还有更多的假值,例如,等,但这些是常见的)。所以:nullundefined||""0false-0NaN

description: post.intro ?? post.description,

post.intro只要它存在,您就会使用,否则(如果post.intronullundefined),您将使用post.description.

于 2021-02-10T14:39:36.473 回答
3

在 Gatsby 加载文件之前,Babel 不会编译该gatsby-config.js文件和任何插件代码(或它需要的代码),因此您使用的任何语法都必须由您安装的 Node.js 版本支持。看起来Node.js 14+ 支持??运算符,因此通过运行检查您的 Node 版本node --version

我最喜欢的升级 Node 的方式(我猜你需要这样做)是使用https://www.npmjs.com/package/n

于 2021-02-11T02:18:10.103 回答
-1

添加依赖项以使用 ES2020 功能进行空合并。

npm install --save-dev babel-preset-gatsby
npm i gatsby-plugin-nullish-coalescing-operator @babel/core

添加.babelrc具有以下配置的文件:

{
    "plugins": [
      ["@babel/plugin-proposal-nullish-coalescing-operator"]
    ],
    "presets": [
      [
        "babel-preset-gatsby",
        {
          "targets": {
            "browsers": [">0.25%", "not dead"]
          }
        }
      ]
    ]
  }

确保您正在运行支持 ES2020 功能的 Node 14.x

于 2021-02-11T03:50:08.287 回答