Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby Config gives error in Javascript file for ?? operator

I am trying to run a Gatsby site but when I do npm run develop, I am getting this error:

> 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,
                           ^

Code:

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,
            }

What is ?? operator in Javscript? Is it a new language feature?

like image 653
Ayman Patel Avatar asked Nov 28 '25 03:11

Ayman Patel


2 Answers

The nullish coalescing operator (??) it's a feature from ECMAScript 2020 (see TC39 proposal). You can add it by modifying the babel configuration or by installing the gatsby-plugin-nullish-coalescing-operator plugin.

If you choose the first version, add a .babelrc in the root of your project and populate it with the following:

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

Note: you will need to install the @babel/plugin-proposal-nullish-coalescing-operator dependency.

What is this operator in Javascript?

The nullish coalescing operator (??), uses the right value if left is null or undefined. The main difference between the OR operator (||) is in the falsy values where it can lead to some errors while used in "", 0 or false values (there are more falsy values such as -0, NaN, etc but those are the common). So:

description: post.intro ?? post.description,

You will use post.intro as long as it exists, otherwise (if post.intro is null or undefined), you will use post.description.

like image 190
Ferran Buireu Avatar answered Nov 30 '25 16:11

Ferran Buireu


The gatsby-config.js file and any plugin code (or code it requires) isn't compiled by Babel before Gatsby loads it so any syntax you use must be supported by the version of Node.js you have installed. It looks like the ?? operator is supported in Node.js 14+ so check your version of Node by running node --version.

My favorite way of upgrading Node (as I'm guessing you'll need to do) is with https://www.npmjs.com/package/n

like image 39
Kyle Mathews Avatar answered Nov 30 '25 16:11

Kyle Mathews



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!