Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature(gatsby): Support TypeScript by default by compiling TS files #23547

Merged
merged 15 commits into from
May 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions docs/docs/typescript.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
---
title: TypeScript and Gatsby
---

## Introductory paragraph

[TypeScript](https://www.typescriptlang.org/) is a JavaScript superset which extends the language to include type definitions allowing codebases to be statically checked for soundness. Gatsby provides an integrated experience out of the box, similar to an IDE. If you are new to TypeScript, adoption can _and should_ be incremental. Since Gatsby natively supports JavaScript and TypeScript, you can change files from .js to .tsx at any point to start adding types and gaining the benefits of a type system.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔥 Yes! This hits all the points I had in mind!


## Example

blainekasten marked this conversation as resolved.
Show resolved Hide resolved
```tsx:title=src/pages/index.js
import React from "react"
import { PageProps } from "gatsby"

export default function IndexRoute(props: PageProps) {
return (
<>
<h1>Path:</h1>
<p>{props.path}</p>
</>
)
}
```

The example above uses the power of TypeScript, in combination with exported types from Gatsby (`PageProps`) to tell this code what props is. This can greatly improve your developer experience by letting your IDE show you what properties are injected by Gatsby. To see all of the types available look at our [TypeScript definition file](https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby/index.d.ts).

## Other resources

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.

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

- [TypeScript Documentation](https://www.typescriptlang.org/docs/handbook/basic-types.html)
- [TypeScript Playground (Try it out!)](https://www.typescriptlang.org/play/index.html)
Copy link
Contributor

@orta orta May 7, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gatsby's API is available in the Playground, so this could be more like this link instead

- [TypeScript Gatsby Example](https://using-typescript.gatsbyjs.org/)
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe(`hot-reloading anonymous arrow functions`, () => {
it(`updates on change`, () => {
const text = `The title`
cy.exec(
`npm run update -- --file src/components/title.js --replacements "TITLE:${text}"`
`npm run update -- --file src/components/title.tsx --replacements "TITLE:${text}"`
)

cy.getTestElement(IDS.title).invoke(`text`).should(`eq`, text)
Expand Down
4 changes: 3 additions & 1 deletion examples/using-typescript/gatsby-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ module.exports = {
exampleUrl: `https://github.com/gatsbyjs/gatsby/tree/master/examples/using-typescript`,
},
plugins: [
`gatsby-plugin-typescript`,
// `gatsby-plugin-typescript` is automatically included in gatsby
// You only need to explicitly define it here if you need to configure
// specific options in it
{
resolve: `gatsby-plugin-typography`,
options: {
Expand Down
1 change: 0 additions & 1 deletion examples/using-typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
"sideEffects": false,
"dependencies": {
"gatsby": "^2.21.0",
"gatsby-plugin-typescript": "^2.4.0",
"gatsby-plugin-typography": "^2.5.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
Expand Down
17 changes: 3 additions & 14 deletions packages/gatsby-plugin-typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,15 @@

Allows Gatsby to build TypeScript and TSX files. Does NOT run type checking during build (see Caveats).

## Install
This plugin is automatically included in Gatsby. The only reason you would need to explicitly use this plugin is if you need to configure its options.

`npm install gatsby-plugin-typescript`
## How to customize usage

## How to use

1. Include the plugin in your `gatsby-config.js` file.
1. Include the plugin in your `gatsby-config.js` file with the specific options
1. Write your components in TSX or TypeScript.
1. Run TypeScript directly or with a build tool.
1. You're good to go.

`gatsby-config.js`

```javascript
module.exports = {
// ...,
plugins: [`gatsby-plugin-typescript`],
}
```

> When [creating pages programmatically](/docs/programmatically-create-pages-from-data/#creating-pages), you can pass the `.tsx` filename directly as the `component` for [`createPage`](/docs/actions/#createPage).

_**Please note**: If packages don't ship with TypeScript definitions you'll need to manually install those type definitions, e.g. for React. A typical Gatsby project would need: `npm install --save-dev @types/react @types/react-dom @types/node`_
Expand Down
1 change: 1 addition & 0 deletions packages/gatsby/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
"gatsby-core-utils": "^1.2.1",
"gatsby-graphiql-explorer": "^0.4.1",
"gatsby-link": "^2.4.1",
"gatsby-plugin-typescript": "^2.4.0",
"gatsby-plugin-page-creator": "^2.3.1",
"gatsby-react-router-scroll": "^2.3.1",
"gatsby-telemetry": "^1.3.2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,22 @@ Array [
"ssrAPIs": Array [],
"version": "1.0.0",
},
Object {
"browserAPIs": Array [],
"id": "",
"name": "gatsby-plugin-typescript",
"nodeAPIs": Array [
"resolvableExtensions",
"onCreateBabelConfig",
"onCreateWebpackConfig",
],
"pluginOptions": Object {
"plugins": Array [],
},
"resolve": "",
"ssrAPIs": Array [],
"version": "1.0.0",
},
Object {
"browserAPIs": Array [],
"id": "",
Expand Down Expand Up @@ -381,6 +397,22 @@ Array [
"ssrAPIs": Array [],
"version": "1.0.0",
},
Object {
"browserAPIs": Array [],
"id": "",
"name": "gatsby-plugin-typescript",
"nodeAPIs": Array [
"resolvableExtensions",
"onCreateBabelConfig",
"onCreateWebpackConfig",
],
"pluginOptions": Object {
"plugins": Array [],
},
"resolve": "",
"ssrAPIs": Array [],
"version": "1.0.0",
},
Object {
"browserAPIs": Array [],
"id": "",
Expand Down Expand Up @@ -601,6 +633,22 @@ Array [
"ssrAPIs": Array [],
"version": "1.0.0",
},
Object {
"browserAPIs": Array [],
"id": "",
"name": "gatsby-plugin-typescript",
"nodeAPIs": Array [
"resolvableExtensions",
"onCreateBabelConfig",
"onCreateWebpackConfig",
],
"pluginOptions": Object {
"plugins": Array [],
},
"resolve": "",
"ssrAPIs": Array [],
"version": "1.0.0",
},
Object {
"browserAPIs": Array [],
"id": "",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,97 @@ describe(`Load plugins`, () => {

expect(plugins).toMatchSnapshot()
})

describe(`TypeScript support`, () => {
it(`loads gatsby-plugin-typescript if not provided`, async () => {
const config = {
plugins: [],
}

let plugins = await loadPlugins(config)

plugins = replaceFieldsThatCanVary(plugins)
Copy link
Contributor

@wardpeet wardpeet Apr 28, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to create a different helper function here? The one that exists now also check paths property and might cause weird test failures when we might move more plugins as a default.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure. Do you have any suggestions? It seems to work right now.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the same setup we have for gatsby-source-page-creators

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe replaceFieldsThatCanVary should also just do more checks before trying to do pluginOptions.path sanitization (apply it only for gatsby-plugin-page-creator)?

But this doesn't seem to be concern of this pull request?


expect(plugins).toEqual(
expect.arrayContaining([
expect.objectContaining({
browserAPIs: [],
id: ``,
name: `gatsby-plugin-typescript`,
nodeAPIs: [
`resolvableExtensions`,
`onCreateBabelConfig`,
`onCreateWebpackConfig`,
],
pluginOptions: {
plugins: [],
},
resolve: ``,
ssrAPIs: [],
version: `1.0.0`,
}),
])
)
})

it(`uses the user provided plugin-typescript if provided`, async () => {
const config = {
plugins: [
{
resolve: `gatsby-plugin-typescript`,
options: {
jsxPragma: `h`,
},
},
],
}

let plugins = await loadPlugins(config)

plugins = replaceFieldsThatCanVary(plugins)

expect(plugins).toEqual(
expect.arrayContaining([
expect.objectContaining({
browserAPIs: [],
id: ``,
name: `gatsby-plugin-typescript`,
nodeAPIs: [
`resolvableExtensions`,
`onCreateBabelConfig`,
`onCreateWebpackConfig`,
],
pluginOptions: {
plugins: [],
jsxPragma: `h`,
},
resolve: ``,
ssrAPIs: [],
version: `1.0.0`,
}),
])
)
blainekasten marked this conversation as resolved.
Show resolved Hide resolved
})

it(`does not add gatsby-plugin-typescript if it exists in config.plugins`, async () => {
const config = {
plugins: [
`gatsby-plugin-typescript`,
{ resolve: `gatsby-plugin-typescript` },
],
}

let plugins = await loadPlugins(config)

plugins = replaceFieldsThatCanVary(plugins)

const tsplugins = plugins.filter(
plugin => plugin.name === `gatsby-plugin-typescript`
)

// TODO: I think we should probably be de-duping, so this should be 1.
// But this test is mostly here to ensure we don't add an _additional_ gatsby-plugin-typescript
pieh marked this conversation as resolved.
Show resolved Hide resolved
expect(tsplugins.length).toEqual(2)
})
})
})
15 changes: 15 additions & 0 deletions packages/gatsby/src/bootstrap/load-plugins/load.js
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,21 @@ const loadPlugins = (config = {}, rootDir = null) => {
}
}

// TypeScript support by default! use the user-provided one if it exists
const typescriptPlugin = (config.plugins || []).find(
plugin =>
plugin.resolve === `gatsby-plugin-typescript` ||
plugin === `gatsby-plugin-typescript`
pieh marked this conversation as resolved.
Show resolved Hide resolved
)

if (typescriptPlugin === undefined) {
plugins.push(
processPlugin({
resolve: require.resolve(`gatsby-plugin-typescript`),
})
)
}

plugins.push(
processPlugin({
resolve: require.resolve(`gatsby-plugin-page-creator`),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
// Gatsby supports TypeScript natively!
import React from "react"
import { Link, graphql } from "gatsby"
import { PageProps, Link, graphql } from "gatsby"

import Bio from "../components/bio"
import Layout from "../components/layout"
import SEO from "../components/seo"
import { rhythm } from "../utils/typography"

const BlogIndex = ({ data, location }) => {
type Data = {
site: {
siteMetadata: {
title: string
}
}
allMarkdownRemark: {
edges: {
node: {
excerpt: string
frontmatter: {
title: string
date: string
description: string
}
fields: {
slug: string
}
}
}[]
}
}

const BlogIndex = ({ data, location }: PageProps<Data>) => {
const siteTitle = data.site.siteMetadata.title
const posts = data.allMarkdownRemark.edges

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
// Gatsby supports TypeScript natively!
import React from "react"
import { Link } from "gatsby"
import { PageProps, Link } from "gatsby"

import Layout from "../components/layout"
import SEO from "../components/seo"

const SecondPage = () => (
const SecondPage = (props: PageProps) => (
<Layout>
<SEO title="Page two" />
<h1>Hi from the second page</h1>
<p>Welcome to page 2</p>
<p>Welcome to page 2 ({props.path})</p>
<Link to="/">Go back to the homepage</Link>
</Layout>
)
Expand Down
2 changes: 2 additions & 0 deletions www/src/data/sidebars/doc-links.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,8 @@
link: /docs/testing-react-components/
- title: Visual Testing with Storybook
link: /docs/visual-testing-with-storybook/
- title: TypeScript
link: /docs/typescript
- title: Debugging Gatsby
link: /docs/debugging/
breadcrumbTitle: Debugging
Expand Down