How to set up GatsbyJS with TypeScript

First things

Install TypeScript as dependency:

  • npm:
npm i typescript --save-dev
  • yarn
yarn add typescript -D

After installing, you should initialize TypeScript project by generating tsconfig.json file

tsc --init

Because in GatsbyJS you are using React components that includes JSX you should set specific parameter in tsconfig.json:

{
    "compilerOptions": {
        ....
        "jsx": "react",
    }
}

If you want to use TypeScript for your src/ files you can easily just rename all files in src/ from .js to .ts or .tsx. Gatsby support TypeScript out of the box.

TypeScript for gatsby-* files

If you want to write files gatsby-browser.js, gatsby-node.js, and others using TypeScript you should install and setup plugin gatsby-plugin-ts-config

Steps:

Installation:

  • npm

npm install -D gatsby-plugin-ts-config

  • yarn
yarn add gatsby-plugin-ts-config -D

Add gatsby-plugin-ts-config into gatsby-config.js

module.exports = {
    plugins: [
      `gatsby-plugin-ts-config`,
    ]
}

Using types in gatsby-node.ts

Read more here (GitHub Gist)

import { GatsbyNode } from "gatsby"

const createPages: GatsbyNode["createPages"] = ({ graphql, actions }) => {
    // something important
}

exports.createPages = createPages
Share:

About

My name is Max, also known as @mxkvl.

I am a software developer, currently working mostly with TypeScript, React and Node ecosystems.

I write a blog about topics that interest me most: programming languages in general, TypeScript, testing, writing and other great stuff.

Join the Mailing List