Skip to content

Latest commit

 

History

History
88 lines (61 loc) · 1.71 KB

How to set up GatsbyJS with TypeScript.md

File metadata and controls

88 lines (61 loc) · 1.71 KB
title tags public date
How to set up GatsbyJS with TypeScript
javascript
gatsbyjs
typescript
true
2020-12-17

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