Gatsby Config & Node API #
After converting all my react components on the site to Typescript I looked around for references to people using Gatsby with Typescript based config.
Finding a Workaround #
The most insightful thing I found was a gist.
Github Gist - JohnAlbin - TypeScript + Gatsby config and node API
Gatsby looks for gatsby-config.js
(javascript) so simply renaming the file will not work.
Instead you need to use ts-node
to load typescript & export all variables from gatsby-config.ts
.
As ts-node
is active Gatsby should then load other gatsby components using the .ts
extension.
ts-node is a TypeScript execution engine and REPL for Node.js.
It JIT transforms TypeScript into JavaScript, enabling you to directly execute TypeScript on Node.js without precompiling.
This is accomplished by hooking node's module loading APIs, enabling it to be used seamlessly alongside other Node.js tools and libraries.
Implementing ts-node in gatsby-config #
gatsby-config.js
require('ts-node').register()
module.exports = require('./gatsby-config.ts')
Gatsby should now reference typescript based config files. (eg: gatsby-node.ts
, gatsby-browser.ts
)
Typescript Config #
tsconfig.json
{
"compilerOptions": {
"module": "CommonJS",
"target": "ESNext",
"lib": [
"DOM",
"ESNext"
],
"strict": true,
"moduleResolution": "node",
"sourceMap": true,
"jsx": "preserve",
"allowJs": true,
"noEmit": true,
"skipLibCheck": true,
"esModuleInterop": true,
"noImplicitAny": false,
"forceConsistentCasingInFileNames": true,
"allowSyntheticDefaultImports": true,
},
"exclude": [
"node_modules",
"public",
".cache"
]
}
Source Code #
You can find the full pull request for the above changes of this site on github.
Using Typescript For Gatsby Config & Node API
The source for the site is available on github.
Webmentions
No Comments Yet