GatsbyJSでTypeScriptを使う方法

依存ライブラリを入れる

1
2
$ npm i gatsby-plugin-typescript
$ npm i -D typescript @types/react @types/react-dom @types/node ts-node

gatsby-node.jsの中もTypeScriptにしたいのでts-nodeを含めています。

gatsby-config.jsにプラグインを追記する

1
2
3
module.exports = {
  plugins: [`gatsby-plugin-typescript`]
}

tsconfig.jsonを追加する

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
  "compilerOptions": {
    "esModuleInterop": true,
    "jsx": "preserve",
    "lib": [
      "dom",
      "esnext"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noUnusedLocals": true,
    "noImplicitReturns": true,
    "noUnusedParameters": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "target": "esnext",
    "allowJs": true,
    "resolveJsonModule": true,
    "isolatedModules": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "./src/**/*",
    "./gatsby/**/*"
  ]
}

gatsby/以下にはgatsby-node.js等の中身をおいていくのでincludeに含めています。

gatsby-config.js内でts-nodeを登録する

gatsby-config.js

1
require("ts-node").register();

gatsby-node.jsの中身をtsにする

gatsby-node.js

1
2
3
4
5
6
const { createPages, onCreateNode } = require('./gatsby/node/').default

module.exports = {
  createPages,
  onCreateNode
}

gatsby/node/index.ts

1
2
3
4
5
6
7
import createPages from './createPages'
import onCreateNode from './onCreateNode'

export default {
  createPages,
  onCreateNode
}

参考サイト等

Built with Hugo
テーマ StackJimmy によって設計されています。