NextJS + Typescript + Tailwind, blazing fast web development

NextJS is one of my favourite React frameworks, is stupidly fast, easy to use, and is already optimized for production, but if you combine it with Typescript, the results are even better.

In this tutorial we are going to setup a NextJS project with Typescript support, and we are going to add (optional) some tools that i like to use and will speed up our development workflow.

If you don’t want to read all the tutorial, the project is here in github.

Creating our NextJS project

The first thing is to create our project, we are going to use yarn as our package manager, this part is already in next docs, here

npx create-next-app

And we can start our project with yarn dev

Adding Typescript

We need some dependencies, and typings

yarn add --dev typescript @types/react @types/node

The next step is add a tsconfig file

tsc --init

This will generate a tsconfig.json in the root of our project with all the TS options.

Important

In order to use TS in your project, you will need to rename your files extension, use .tsx instead of .js.

Usually this is the configuration that i tend to use:

tsconfig.json
{
  "compilerOptions": {
    "jsx": "preserve",
    "allowJs": true,
    "alwaysStrict": true,
    "skipLibCheck": true,
    "target": "esnext",
    "noEmit": true,
    "moduleResolution": "node",
    "module": "esnext",
    "noUnusedParameters": true,
    "isolatedModules": true,
    "lib": [
      "dom",
      "es2017"
    ],
    "esModuleInterop": true,
    "baseUrl": "./",
    "paths": {
      // We will configure this later, is one of my favourites TS options
    },
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true
  },
  "exclude": ["node_modules"],
  "include": ["**/*.ts", "**/*.tsx"]
}

Configuring TS paths

Ts paths is a really useful utility, it works as an alias, they let you go from this:

import { moduleA } from '../../../../../../modules/a';

To this:

import { moduleA } from '@modules/a';

Here is the project structure that i’m going to use

NextJS + Typescript project structure

So in order to add tspaths to replicate this structure, we need to add them to our tsconfig file

tsconfig.json
{
  "compilerOptions": {
    // Other tsconfig options
    "paths": {
      // name_of_alias: [real_path_of_directory]
      "@components/*": ["./src/components/*"],
      "@hooks/*": ["./src/hooks/*"],
      "@typings/*": ["./src/typings/*"],
      "@utils/*": ["./src/utils/*"]
    }
  },
  "exclude": ["node_modules"],
  "include": ["**/*.ts", "**/*.tsx"]
}

Adding TailwindCSS (optional)

TailwindCSS is a CSS utils based framework, it let you define your entire layout with almost no CSS, they provide utility classes that you can use to build your structure.

First add the TailwindCSS dependencies, postcss, autoprefixer, node-sass and next-sass so we can use SASS in our project

yarn add tailwindcss postcss-import autoprefixer @zeit/next-sass node-sass

Create a tailwind.config.js file:

touch tailwind.config.js

And inside we are going to add this:

tailwind.config.js
module.exports = {
  purge: ['./src/components/**/*.tsx', './pages/**/*.tsx'],
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
};

We can configure this file as we want, you can read more about this in the Tailwind docs

We need a postcss.config.js file too, create one in the project root and add this:

postcss.config.js
module.exports = {
  plugins: ['tailwindcss', 'postcss-preset-env'],
};

And lastly, we are going to modify the next config to use SASS instead of CSS.

Create a file called next.config.js, this is the config we need in order to use tailwindCSS and SASS in our project

next.config.js
const withSass = require("@zeit/next-sass");
const tailwindCss = require("tailwindcss");

module.exports = withSass({
  webpack(config) {
    const rules = [
      {
        test: /\.scss$/,
        use: [
          {
            loader: "postcss-loader",
            options: {
              ident: "postcss",
              plugins: [tailwindCss("./tailwind.config.js")],
            },
          },
          { loader: "sass-loader" },
        ],
      },
    ];
    if (!config.resolve.plugins) {
      config.resolve.plugins = [];
    }

    return {
      ...config,
      module: { ...config.module, rules: [...config.module.rules, ...rules] },
    };
  },
});

Importing TailwindCSS

Right now tailwindCSS is not loaded yet into our styles

Create a file in ./src/styles and call it index.scss, inside import tailwind

./src/styles/index.scss
@import "~tailwindcss/base";
@import "~tailwindcss/components";
@import "~tailwindcss/utilities";

If you want to use this globally, you can import this into your _app.tsx file

// pages/_app.tsx
import "../src/styles/index.scss";

Execute yarn dev and Tailwind will be added to your stylesheet

Now you have a super-fast project configured and ready to work with, and up to date with the 2020 version of Typescript (4.0.2), Next 9.5, and TailwindCSS 1.7