How to set up GatsbyJS with TypeScript

First things

Install TypeScript as dependency:

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

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

1
tsc --init

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

1
2
3
4
5
6
{
  	"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
1
yarn add gatsby-plugin-ts-config -D

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

1
2
3
4
5
module.exports = {
	plugins: [
	  `gatsby-plugin-ts-config`,
	]
}

Using types in gatsby-node.ts

Read more here (GitHub Gist)

1
2
3
4
5
6
7
import { GatsbyNode } from "gatsby"

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

exports.createPages = createPages