loading...

Gatsby Typescript and Sass conf

feralamillo profile image Feralamillo Originally published at Medium on ・5 min read

If you are also very fan of React with Typescript and you want to start working with Gatsby this post is for you. I'm going to cover how to setup the basic environment including Typescript, Sass, linting and prettier for Gatsby.
I have been using React mainly with create-react-app as it is a nice tool that comes ready to use specially with npx create-react-app --template typescript. Recently I see that Gatsby is getting more and more importance so I'm very eager to try it.

Gatsby typescript

The create react app templates are called starters in Gatsby. I have been checking 2 typescript starters comparing with the javascript version and don't provide as much value as the original version:

  • Gatsby starter typescript
  • Gatsby starter typescript plus

Until these projects don't evolve a little bit I'm going to do small modifications to the basic Gatsby. These also has the benefit that the core version is usually better maintained. We are going to set it up in less than 5 minutes with these 3 steps:

  1. Install Gatsby
  2. Install typescript and update configuration
  3. Update files

1. Install Gatsby

Gatsby can be installed globally in your computer and then using the cli commands or you can just use directly npx. I prefer to avoid installing more things so I'll go with the second one. From the terminal:
npx gatsby new <project-name>

This will take a couple of minutes and install all the necessary stuff. When opening the project, you can see inside the srcfolder:

| src
| -- components
| -- images
| -- pages

Components and pages have some javascript files. To verify that everything works you can run npm start and you'll see the app in localhost:8080.
If you want, as Gatsby doesn't come with a git, I suggest that you initialize it at this point.

2. Install typescript and update configuration

To have typescript in gatsby you need to install gatsby-plugin-typescript.

npm i -E gatsby-plugin-typescript

After it's installed, you'll need to update the gatsby config (gatsby-config.js ) including the plugin. The file should look something like this.

// gatsby-config.js
module.exports = {
  siteMetadata: {
    title: `Gatsby Default Starter`,
    description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
    author: `@gatsbyjs`,
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-plugin-typescript`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    },
    // this (optional) plugin enables Progressive Web App + Offline functionality
    // To learn more, visit: https://gatsby.dev/offline
    // `gatsby-plugin-offline`,
  ],
}

Create the file tsconfig.json in the root of the project to include the typescript configuration:

// tsconfig.json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "baseUrl": "src",
    "paths": {
      "src/*" : ["*"],
    }
  },
  "include": ["src"]
}

As before, to verify that everything works, just run npm start and it should work as before. The files are still in javascript so we haven't done much that can break for now.

3. Update files

At this stage, you can just update the .js/.jsx files to .ts/.tsx or, if you have already initialize git, update the filenames using git. Don't worry, here is the code:
Using git:

git mv src/components/header.js src/components/header.tsx
git mv src/components/image.js src/components/image.tsx
git mv src/components/layout.js src/components/layout.tsx
git mv src/components/seo.js src/components/seo.tsx
git mv src/pages/404.js src/pages/404.tsx
git mv src/pages/index.js src/pages/index.tsx
git mv src/pages/page-2.js src/pages/page-2.tsx

Updating the name directly:

mv src/components/header.js src/components/header.tsx
mv src/components/image.js src/components/image.tsx
mv src/components/layout.js src/components/layout.tsx
mv src/components/seo.js src/components/seo.tsx
mv src/pages/404.js src/pages/404.tsx
mv src/pages/index.js src/pages/index.tsx
mv src/pages/page-2.js src/pages/page-2.tsx

Last thing, for the formatting with prettier, you also need to update the scripts section in package.json:

"scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write \"**/*.{tsx,ts,js,jsx,json,md}\"",
    "start": "npm run develop",
    "serve": "gatsby serve",
    "clean": "gatsby clean",
    "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1"
  },

Now you can do npm start to verify that everything works as expected.

Gatsby with Sass

1. Install dependencies

We need to install node-sass and the plugin gatsby-plugin-sass so it can work.

npm i -E gatsby-plugin-sass node-sass

2. Update gatsby config

Include the plugin gatsby-plugin-sass in the gatsby configuration.

// gatsby-config.js
module.exports = {
  siteMetadata: {
    title: `Gatsby Default Starter`,
    description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
    author: `@gatsbyjs`,
  },
  plugins: [
    `gatsby-plugin-sass`,
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-plugin-typescript`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    },
    // this (optional) plugin enables Progressive Web App + Offline functionality
    // To learn more, visit: https://gatsby.dev/offline
    // `gatsby-plugin-offline`,
  ],
}

3. Update files

Once the configuration has updated, we can change the .css files to .scss. In the initial installation of gatsby there is only one file which is the layout:

git mv src/components/layout.css src/components/layout.scss

Remeber to also update the import of this file. It only shows in src/components/layout.tsx

/**
 * Layout component that queries for data
 * with Gatsby's useStaticQuery component
 *
 * See: https://www.gatsbyjs.org/docs/use-static-query/
 */
import React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import Header from "./header"
import "./layout.scss"

Bob's your uncle! You can verify that everything works doing npm start

Improvements

As usual, there is always room for improvement. If you have any ideas or suggestions please leave a comment below.

Posted on by:

Discussion

markdown guide
 

Thanks a lot for this tutorial. While I have been working with TS for a while, I just started working with react/gatsby (read: I'm following tutorials).

My impulse is to set up the project the way you mentioned it, and as I go through tutorials, adapt them to TS.

Since I'm building a personal project, mostly to learn, I am aiming for Gatsby with GraphQL. Would you recommend I go with TS and Sass, or stick to JS + class styling? (looking for a personal opinion, not the objective truth)