In Prod

← Back to Posts

Gatsby with Typescript

February 08, 2020

Out of the box, Gatsby uses javascript as it's default language. However, there is an official plugin that can be used to add Typescript support, which allows us to use tsx for React components.


Installing Typescript for Gatsby

Install the gatsby-plugin-typescript along with typescript and some required types:


_1
yarn add typescript gatsby-plugin-typescript @types/node @types/react @types/react-dom @types/react-helmet


Configure

Next we need to add these packages to the gatsby-config.js file.

gatsby-config.js

_7
module.exports = {
_7
// ...metadata
_7
plugins: [
_7
// ...rest
_7
'gatsby-plugin-typescript',
_7
],
_7
}

All javascript files will now need to have their extension changed from js/jsx to ts/tsx.

The Gatsby API files in the root of the project currently need to remain as javascript files:

  • gatsby-browser.js
  • gatsby-config.js
  • gatsby-node.js
  • gatsby-ssr.js

If you run yarn serve at this point the project should build and display fine.


Andrew McMahon
These are a few of my insignificant productions
by Andrew McMahon.