Skip to content

Commit 04d1d37

Browse files
LekoArtsmarvinjudetyhopppiehgatsbybot
authoredFeb 28, 2022
feat(gatsby): Compile Gatsby Config Files AOT (#34776)
* get simplest gatsby-config.ts working * make gatsby-node work * use program.directory for default-site-plugin for browser/ssr * chore(docs): update TS doc (#34757) Co-authored-by: LekoArts <[email protected]> * feat(gatsby-parcel-config): create parcel config package (#34779) Co-authored-by: Lennart <[email protected]> * refactor(core): Polish ahead of time ts implementation (#34773) Co-authored-by: LekoArts <[email protected]> * tmp * update parcel deps version * update snapshot * merge master * feat(core): TS compilation of local plugin gatsby files (#34827) Co-authored-by: LekoArts <[email protected]> * Update scaling-issues.md * Restore build.js * Restore develop.js * Restore repl.js * set flag to always true * chore(docs): update main tutorial to incorporate TS Updates to create-gatsby (#34890) Co-authored-by: Lennart <[email protected]> * chore(gatsby): compile only TS files (#34892) * use require resolve for defaultConfig * update doc to add limitations and migration guides * add structured error logging * fix cache reslience setup (#34915) * bump @parcel/source-map in monorepo lock * adjust tests so cache dirs are cleared only before compilations to workaround EBUSY problems on Windows * address review comments * docs: specify gatsby versions supporting particular TS features (#34945) Co-authored-by: Lennart <[email protected]> Co-authored-by: Jude Agboola <[email protected]> Co-authored-by: Ty Hopp <[email protected]> Co-authored-by: Michal Piechowiak <[email protected]> Co-authored-by: gatsbybot <[email protected]>
1 parent cf5f9c3 commit 04d1d37

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+1507
-80
lines changed
 

‎.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,5 @@ package-lock.json
6565
!themes/gatsby-starter-notes-theme/package-lock.json
6666
!themes/gatsby-starter-theme/package-lock.json
6767
!themes/gatsby-starter-theme-workspace/package-lock.json
68+
69+
.parcel-cache

‎docs/docs/how-to/custom-configuration/typescript.md

+206-14
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ title: TypeScript and Gatsby
33
examples:
44
- label: Using Typescript
55
href: "https://github.com/gatsbyjs/gatsby/tree/master/examples/using-typescript"
6+
- label: Using vanilla-extract
7+
href: "https://github.com/gatsbyjs/gatsby/tree/master/examples/using-vanilla-extract"
68
---
79

810
## Introduction
@@ -11,11 +13,27 @@ examples:
1113

1214
To see all of the types available and their generics look at our [TypeScript definition file](https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby/index.d.ts).
1315

14-
## `PageProps`
16+
## Initializing a new project with TypeScript
17+
18+
You can get started with TypeScript and Gatsby by using the CLI:
19+
20+
```
21+
npm init gatsby
22+
```
23+
24+
In the prompts, select TypeScript as your preferred language. You can also pass a `ts` flag to the above command to skip that question and use TypeScript:
25+
26+
```
27+
npm init gatsby -ts
28+
```
29+
30+
## Usage in Gatsby
31+
32+
### `PageProps`
1533

1634
```tsx:title=src/pages/index.tsx
1735
import * as React from "react"
18-
import { PageProps } from "gatsby"
36+
import type { PageProps } from "gatsby"
1937

2038
const IndexRoute = ({ path }: PageProps) => {
2139
return (
@@ -65,15 +83,19 @@ export const query = graphql`
6583
`
6684
```
6785

68-
## `gatsby-browser.tsx` / `gatsby-ssr.tsx`
86+
### `gatsby-browser.tsx` / `gatsby-ssr.tsx`
87+
88+
> Support added in `gatsby@4.8.0`
6989
7090
You can also write `gatsby-browser` and `gatsby-ssr` in TypeScript. You have the types `GatsbyBrowser` and `GatsbySSR` available to type your API functions. Here are two examples:
7191

7292
```tsx:title=gatsby-browser.tsx
7393
import * as React from "react"
74-
import { GatsbyBrowser } from "gatsby"
94+
import type { GatsbyBrowser } from "gatsby"
7595

76-
export const wrapPageElement: GatsbyBrowser["wrapPageElement"] = ({ element }) => {
96+
export const wrapPageElement: GatsbyBrowser["wrapPageElement"] = ({
97+
element,
98+
}) => {
7799
return (
78100
<div>
79101
<h1>Hello World</h1>
@@ -85,7 +107,7 @@ export const wrapPageElement: GatsbyBrowser["wrapPageElement"] = ({ element }) =
85107

86108
```tsx:title=gatsby-ssr.tsx
87109
import * as React from "react"
88-
import { GatsbySSR } from "gatsby"
110+
import type { GatsbySSR } from "gatsby"
89111

90112
export const wrapPageElement: GatsbySSR["wrapPageElement"] = ({ element }) => {
91113
return (
@@ -97,13 +119,13 @@ export const wrapPageElement: GatsbySSR["wrapPageElement"] = ({ element }) => {
97119
}
98120
```
99121

100-
## `getServerData`
122+
### `getServerData`
101123

102124
You can use `GetServerData`, `GetServerDataProps`, and `GetServerDataReturn` for [`getServerData`](/docs/reference/rendering-options/server-side-rendering/).
103125

104-
```tsx:src/pages/ssr.tsx
126+
```tsx:title=src/pages/ssr.tsx
105127
import * as React from "react"
106-
import { GetServerDataProps, GetServerDataReturn } from "gatsby"
128+
import type { GetServerDataProps, GetServerDataReturn } from "gatsby"
107129

108130
type ServerDataProps = {
109131
hello: string
@@ -133,12 +155,182 @@ const getServerData: GetServerData<ServerDataProps> = async props => {
133155
}
134156
```
135157

136-
## Other resources
158+
### `gatsby-config.ts`
159+
160+
> Support added in `gatsby@4.9.0`
161+
162+
You can import the type `GatsbyConfig` to type your config object. **Please note:** There are currently no type hints for `plugins` and you'll need to check the [current limitations](#current-limitations) and see if they apply to your `gatsby-config` file.
163+
164+
```ts:title=gatsby-config.ts
165+
import type { GatsbyConfig } from "gatsby"
166+
167+
const config: GatsbyConfig = {
168+
siteMetadata: {
169+
title: "Your Title",
170+
},
171+
plugins: [],
172+
}
173+
174+
export default config
175+
```
176+
177+
### `gatsby-node.ts`
178+
179+
> Support added in `gatsby@4.9.0`
180+
181+
You can import the type `GatsbyNode` to type your APIs by accessing keys on `GatsbyNode`, e.g. `GatsbyNode["sourceNodes"]`. **Please note:** You'll need to check the [current limitations](#current-limitations) and see if they apply to your `gatsby-node` file.
182+
183+
```ts:title=gatsby-node.ts
184+
import type { GatsbyNode } from "gatsby"
185+
186+
type Person = {
187+
id: number
188+
name: string
189+
age: number
190+
}
191+
192+
export const sourceNodes: GatsbyNode["sourceNodes"] = async ({
193+
actions,
194+
createNodeId,
195+
}) => {
196+
const { createNode } = actions
197+
198+
const data = await getSomeData()
199+
200+
data.forEach((person: Person) => {
201+
const node = {
202+
...person,
203+
parent: null,
204+
children: [],
205+
id: createNodeId(`person__${person.id}`),
206+
internal: {
207+
type: "Person",
208+
content: JSON.stringify(person),
209+
contentDigest: createContentDigest(person),
210+
},
211+
}
212+
213+
createNode(node)
214+
})
215+
}
216+
```
217+
218+
### Local Plugins
219+
220+
> Support added in `gatsby@4.9.0`
221+
222+
All the files mentioned above can also be written and used inside a [local plugin](/docs/creating-a-local-plugin/).
223+
224+
## `tsconfig.json`
225+
226+
Essentially, the `tsconfig.json` file is used in tools external to Gatsby e.g Testing Frameworks like Jest, Code editors and Linting libraries like EsLint to enable them handle TypeScript correctly. You can use the `tsconfig.json` from our [gatsby-minimal-starter-ts](https://github.com/gatsbyjs/gatsby/blob/master/starters/gatsby-starter-minimal-ts/tsconfig.json).
227+
228+
## Type Hinting in JS Files
229+
230+
You can still take advantage of type hinting in JavaScript files with [JSdoc](https://jsdoc.app/) by importing types directly from Gatsby. You need to use a text exitor that supports those type hints.
231+
232+
### Usage in `gatsby-config.js`
233+
234+
```js:title=gatsby-config.js
235+
// @ts-check
236+
237+
/**
238+
* @type {import('gatsby').GatsbyConfig}
239+
*/
240+
const gatsbyConfig = {}
241+
242+
module.exports = gatsbyConfig
243+
```
244+
245+
### Usage in `gatsby-node.js`
246+
247+
```js:title=gatsby-node.js
248+
// @ts-check
249+
250+
/**
251+
* @type {import('gatsby').GatsbyNode['createPages']}
252+
*/
253+
exports.createPages = () => {}
254+
```
255+
256+
## Styling
257+
258+
[vanilla-extract](https://vanilla-extract.style/) helps you write type‑safe, locally scoped classes, variables and themes. It's a great solution when it comes to styling in your TypeScript project. To use vanilla-extract, select it as your preferred styling solution when initializing your project with `npm init gatsby`. You can also manually setup your project through [gatsby-plugin-vanilla-extract](/plugins/gatsby-plugin-vanilla-extract/) or use the [vanilla-extract example](https://github.com/gatsbyjs/gatsby/tree/master/examples/using-vanilla-extract).
259+
260+
## Migrating to TypeScript
261+
262+
Gatsby natively supports JavaScript and TypeScript, you can change files from `.js`/`.jsx` to `.ts`/ `tsx` at any point to start adding types and gaining the benefits of a type system. But you'll need to do a bit more to be able use Typescipt in `gatsby-*` files:
263+
264+
- Run `gatsby clean` to remove any old artifacts
265+
- Convert your `.js`/`.jsx` files to `.ts/.tsx`
266+
- Install `@types/node`, `@types/react`, `@types/react-dom`, `typescript` as `devDependencies`
267+
- Add a `tsconfig.json` file using `npx tsc init` or use the one from [gatsby-minimal-starter-ts](https://github.com/gatsbyjs/gatsby/blob/master/starters/gatsby-starter-minimal-ts/tsconfig.json)
268+
- Rename `gatsby-*` files:
269+
- `gatsby-node.js` to `gatsby-node.ts`
270+
- `gatsby-config.js` to `gatsby-config.ts`
271+
- `gatsby-browser.js` to `gatsby-browser.tsx`
272+
- `gatsby-ssr.js` to `gatsby-ssr.tsx`
273+
- Address any of the [current limitations](#current-limitations)
274+
275+
## Current limitations
276+
277+
There are some limitations currently that you need to be aware of. We'll do our best to mitigate them in our code or through contributions to upstream dependencies.
278+
279+
### Parcel TypeScript features
280+
281+
Parcel is used for the compilation and it currently has [limitations on TypeScript features](https://parceljs.org/languages/typescript/), namely:
282+
283+
- No support for `baseUrl` or `paths` inside `tsconfig.json`
284+
- It implicitly enables the [`isolatedModules`](https://www.typescriptlang.org/tsconfig#isolatedModules) option by default
285+
286+
### `__dirname`
287+
288+
You can't use `__dirname` and `__filename` in your files. You'll need to replace these instances with a `path.resolve` call. Example diff for a `gatsby-config` file:
289+
290+
```diff
291+
+ import path from "path"
292+
293+
const config = {
294+
plugins: [
295+
{
296+
resolve: `gatsby-source-filesystem`,
297+
options: {
298+
name: `your-name`,
299+
+ path: path.resolve(`some/folder`),
300+
- path: `${__dirname}/some/folder`,
301+
},
302+
},
303+
]
304+
}
305+
306+
export default config
307+
```
308+
309+
Progress on this is tracked in [Parcel #7611](https://github.com/parcel-bundler/parcel/issues/7611).
310+
311+
### `require.resolve`
312+
313+
You can't use `require.resolve` in your files. You'll need to replace these instances with a `path.resolve` call. Example diff for a `gatsby-node` file:
314+
315+
```diff
316+
+ import path from "path"
317+
318+
+ const template = path.resolve(`src/templates/template.tsx`)
319+
- const template = require.resolve(`./src/templates/template.tsx`)
320+
```
321+
322+
Progress on this is tracked in [Parcel #6925](https://github.com/parcel-bundler/parcel/issues/6925).
323+
324+
### Other
325+
326+
- Workspaces (e.g. Yarn) are not supported yet.
327+
- When changing `siteMetadata` in `gatsby-config` no hot-reloading will occur during `gatsby develop`. A restart is needed at the moment.
328+
329+
## Other Resources
137330

138-
TypeScript integration is supported through automatically including [`gatsby-plugin-typescript`](/plugins/gatsby-plugin-typescript/). Visit that link to see configuration options and limitations of this setup.
331+
TypeScript integration for pages is supported through automatically including [`gatsby-plugin-typescript`](/plugins/gatsby-plugin-typescript/). Visit that link to see configuration options and limitations of this setup.
139332

140333
If you are new to TypeScript, check out these other resources to learn more:
141334

142-
- [TypeScript Documentation](https://www.typescriptlang.org/docs/handbook/basic-types.html)
143-
- [TypeScript Playground (Try it out!)](https://www.typescriptlang.org/play/index.html)
144-
- [TypeScript Gatsby Example](https://using-typescript.gatsbyjs.org/)
335+
- [TypeScript Documentation](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html)
336+
- [TypeScript Playground (Try it out!)](https://www.typescriptlang.org/play)

0 commit comments

Comments
 (0)
Please sign in to comment.