Setup NextJS with typescript, EsLint, prettier and husky
Tags: webdev, tutorial, programming, javascript
Published: 2022-06-06 12:01:36

This is a short blog on setting up a project with NextJS, EsLint, prettier and husky.

- Next.js is a React framework that gives you building blocks to create web applications.

- EsLint is a pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Maintain your code quality with ease.

- Prettier is an opinionated code formatter that supports many different programming languages, like JavaScript. JSON. JSX.

- Husky improves your git commits and more 🐶 woof!

## 01 Setting up Nextjs with typescript

```
npx create-next-app [project-name] --typescript
```

this will setup nextjs project for you

## 02 Setting up Eslint in the project
eslint comes pre-setup through `npx create-next-app ` we don't have to install eslint simply run the below command in your terminal

```
npm init @eslint/config
```

which will guide you through a series of configuration settings

a. How would you like to use ESLint?

- To check syntax only
- To check syntax and find problems
- To check syntax, find problems, and enforce code style

> To check syntax, find problems, and enforce code style

since we not only want to find problems in our code we want to enforce a common code style (Airbnb)

b. What type of modules does your project use?

- JavaScript modules (import/export)
- CommonJS (require/exports)
- None of these

> JavaScript modules (import/export)

- Note JavaScript modules (import/export): The ES module format is the official standard format to package JavaScript code for reuse and most modern web browsers natively support the modules.

- Note Node.js, however, supports the CommonJS module format by default. CommonJS modules-load using require(), and variables and functions export from a CommonJS module with module.exports.

c. Which framework does your project use?

- React
- Vue.js
- None of these

> React

d. Does your project use TypeScript?

- yes/no

> yes

e. Where does your code run?

- Browser
- Node

> Browser

f. How would you like to define a style for your project?

- Use a popular style guide
- Answer questions about your style

> Use a popular style guide

> Airbnb: https://github.com/airbnb/javascript

Since Airbnb is the most popular style guide and industry standard in most companies.

g. What format do you want your config file to be in?

- JavaScript
- YAML
- JSON

> JSON

We will select JSON because it is preferred over other file formats

h. Would you like to install them now?

- No / Yes

> Yes

i. Which package manager do you want to use?
- npm
- yarn
- pnpm

> npm

## 03 Now let's Setup prettier
First lets install necessary packages for setting up prettier in our project

```
npm install prettier eslint-config-prettier eslint-plugin-prettier --save-dev
```

Then go to `.eslintrc.json` file and add following configurations to `"extends"` property and `"plugins"` property

> NOTE The extends property value is either: a string that specifies a configuration(either a path to a config file, the name of a shareable config, eslint: recommended, or eslint: all ) or an array of strings where each additional configuration extends the preceding configurations.

```
{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "plugin:react/recommended",
    "next/core-web-vitals",
    "airbnb",
    "plugin:prettier/recommended"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": ["react", "@typescript-eslint", "prettier"],
  "rules": {}
}

```
- Now let's create a local prettier configuration file
```
touch .prettierrc
```
- And then add the following configuration to the `.prettierrc` file.
```
{
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": false,
  "trailingComma": "es5",
  "printWidth": 80
}
```
> Install prettier in your local code editor in my case I'm using vscode.
> Then go to vscode settings and search for `Default Formatter` change it to `Prettier-Code formatter`.

> after that make sure `format on save` is turned on in your vscode settings this will format your code every time you save your file.

## 04. Now let's configure eslint rules to our liking
first, let's install the package for Airbnb typescript configuration 

```
npm install eslint-config-airbnb-typescript --save-dev
```

- Then add configurations to the `.eslintrc.json` file

```
{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "plugin:react/recommended",
    "next/core-web-vitals",
    "airbnb",
    "airbnb-typescript",
    "plugin:prettier/recommended"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module",
    "project": "./tsconfig.json"
  },
  "plugins": ["react", "@typescript-eslint", "prettier"],
  "rules": {
    // suppress errors for missing 'import React' in files
    "react/react-in-jsx-scope": ["off"],
    // gives warning if spread props getting passed to component ex. (...props)
    "react/jsx-props-no-spreading": ["warn"],
    // suppress errors for Function component is not a function declaration turning off allows us to use arrow functions
    "react/function-component-definition": ["off"]
  }
}

```

- Now add scripts in our `package.json` file

```
  {
  "name": "final",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "check-format": "prettier --check .",
    "check-lint": "eslint . --ext ts --ext tsx --ext js",
    "check-types": "tsc --pretty --noEmit",
    "format": "prettier --write ."
  },
  "dependencies": {
    "next": "12.1.6",
    "react": "18.1.0",
    "react-dom": "18.1.0"
  },
  "devDependencies": {
    "@types/node": "17.0.40",
    "@types/react": "18.0.12",
    "@types/react-dom": "18.0.5",
    "@typescript-eslint/eslint-plugin": "^5.27.0",
    "@typescript-eslint/parser": "^5.27.0",
    "eslint": "^8.17.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-airbnb-typescript": "^17.0.0",
    "eslint-config-next": "12.1.6",
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-jsx-a11y": "^6.5.1",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.30.0",
    "eslint-plugin-react-hooks": "^4.5.0",
    "prettier": "^2.6.2",
    "typescript": "4.7.3"
  }
}

```

- Now let's add `.eslintignore` and `.prettierignore` file at the root of our project

```
touch .eslintignore .prettierignore
```

- Then ignore the following files and folder in both files

`/node_modules
 next.config.js
 .next
`

- Now run scripts to check if any error is being thrown

```
npm run format
```

```
npm run check-format && npm run check-lint
```

If all things went well no error should be thrown.

## 05. Now, let's set up husky in our project.
First, run the following command in terminal

```
npx husky-init && npm install
```

This should setup husky in our project

- Now add some configuration to our `pre-commit` file under `.husky` folder.

```
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

echo '🏗️👷 Styling, testing and building your project before committing'

# Check Prettier standards
npm run check-format ||
(
    echo '🤢🤮🤢🤮
                Yaaaaaccccccckkkkkkkkkk 🤢🤮🤢🤮
            Prettier Check Failed. Please Run npm run format, add changes and try commit again.';
    false;
)

# Check ESLint Standards
npm run check-lint ||
(
        echo '😤🏀👋😤 Bla Bla Bla Bla 😤🏀👋😤 
                ESLint Check Failed. Make the required changes listed above, add changes and try to commit again.'
        false; 
)

# Check tsconfig standards
npm run check-types ||
(
    echo '🤡😂❌🤡 Failed to check the types. 🤡😂❌🤡
            Please Make the changes required above.'
    false;
)

# If everything passes... Now we can commit
echo '🤔🤔🤔🤔... Alright.... Code looks good to me... Trying to build now. 🤔🤔🤔🤔'

npm run build ||
(
    echo '❌👷🔨❌ Send Help Build has failed ❌👷🔨❌
            Next build failed: View the errors above to see why. 
    '
    false;
)

# If everything passes... Now we can commit
echo '✅✅✅✅ Yo you got this... I am committing this now. ✅✅✅✅'
```

- Now try to commit the following checks should be automatically done in our project before committing

```
git add .
git commit -m 'test'
```

If all went well you should be able to commit your changes to your file