How to setup Nextjs with Eslint and Prettier

This is a simple guide to setup Nextjs with Eslint, Prettier and a Simple Imports Sort plugin. Nextjs already comes with Eslint however we are going to add some extra dependencies to work with Prettier.

Requirements

If you are using Visual Studio Code, you should have the following plugins installed:

  • eslint
  • prettier

You'll need these if you want to auto format your files and to format any files manually.

Npm packages we will be importing are:

The Setup

To install the required dependencies copy the code below and paste into your terminal. I am using Yarn in this example but you can replace it with npm instead. We are installing these npm packages as dev dependencies.

yarn add -D eslint-config-prettier eslint-plugin-prettier eslint-plugin-simple-import-sort prettier

Next we want to update the existing .eslingrc.json file with the following configuration.

{
  "extends": [
    "next/core-web-vitals",
    "plugin:prettier/recommended"
  ],
  "plugins": ["simple-import-sort"],
  "rules": {
    "simple-import-sort/imports": "error",
    "simple-import-sort/exports": "error",
    "import/first": "error",
    "import/newline-after-import": "error",
    "import/no-duplicates": "error",
    "prettier/prettier": [
      "error",
      {
        "endOfLine": "auto"
      }
    ]
  }
}

The "prettier/prettier" rule is meant to resolve errors that may appear in VSCode when CRLF is select.

Finally we want to add a .pretterrc file to the root of your application. It should be added wherever your .eslintrc.json file is located.

{
  "printWidth": 100,
  "tabWidth": 2,
  "singleQuote": true,
  "trailingComma": "all",
  "proseWrap": "always",
  "overrides": [
    {
      "files": "*.json",
      "options": {
        "printWidth": 999999
      }
    }
  ]
}

And that is all that is needed. Now when you are working on your Nextjs project you will see error highlighting and you can auto-fix any issues that may crop up.