I've been on a Typescript kick lately and integrating it into all of my projects and workflows. With Gatsby it's honestly as simple as installing a plugin, but I thought I'd document the minimal nuances there are in the process.
- Install Typescript, typings for React/Node, ESLint (and default config + prettier integration), and finally the Gatsby plugin for Typescript support:
npm i typescript gatsby-plugin-typescript
npx install-peerdeps --dev eslint-config-airbnb
npm install --save-dev @types/react @types/react-dom @types/node eslint eslint-config-prettier eslint-plugin-prettier
- Add the following plugin to your
gatsby-config.js
:
module.exports = {
// ...,
plugins: [...`gatsby-plugin-typescript`],
};
- Add linting and type checking scripts to your
package.json
:
{
"scripts": {
"lint": "eslint . --ext ts --ext tsx'",
"test": "npm run type-check && npm run lint",
"type-check": "tsc --pretty --noEmit"
},
}
- Create a
tsconfig.json
in the root of your project. I grabbed mine from here, but there are plenty on Github to reference (like this):
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"baseUrl": "./src",
"jsx": "react",
"lib": ["dom", "esnext", "es2015", "es2016", "es2017"],
"moduleResolution": "node",
"noImplicitAny": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"plugins": [
{
"name": "typescript-styled-plugin"
}
],
"target": "es2015"
},
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["node_modules/*", "public/*"]
}
References
- https://basarat.gitbooks.io/typescript/
- https://www.reactandtypescript.dev/installation/gatsby
- https://www.gatsbyjs.org/packages/gatsby-plugin-typescript/
- https://github.com/resir014/gatsby-starter-typescript-plus/blob/master/package.json
Software Requirements
| Software | Version | | ------------------------ | ------- | | gatsby-plugin-typescript | 2.1.26 | | gatsby | 2.18.22 | | react | 16.12 |