Reputation: 634
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?
Upvotes: 3
Views: 626
Reputation: 634
Add dependencies to use ES2020 features for null coalescing.
npm install --save-dev babel-preset-gatsby
npm i gatsby-plugin-nullish-coalescing-operator @babel/core
Add .babelrc
file with the following configurations:
{
"plugins": [
["@babel/plugin-proposal-nullish-coalescing-operator"]
],
"presets": [
[
"babel-preset-gatsby",
{
"targets": {
"browsers": [">0.25%", "not dead"]
}
}
]
]
}
Make sure you are running Node 14.x which supports ES2020 features
Upvotes: -1
Reputation: 3278
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
Upvotes: 3
Reputation: 29305
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
.
Upvotes: 4