Prettier and ESLint Configuration in Next.js Projects

September 20, 2024 (3w ago)

Prettier and ESLint Configuration in Next.js Projects

Introduction

In this blog post, we'll walk through the process of setting up Prettier and ESLint in a Next.js project. We'll cover installation, configuration, and some advanced features to help you maintain a consistent and clean codebase.

Setting Up Next.js

First, let's start by installing a new Next.js application. You can do this using the following command:

npx create-next-app@latest

After installation, you'll notice that ESLint is already included in your Next.js project.

ESLint vs. Prettier

Before we dive into the configuration, let's understand the difference between ESLint and Prettier:

  • ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. It's primarily used to catch logical errors and enforce coding standards.
  • Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules.

In essence, ESLint helps with code quality, while Prettier helps with code formatting.

Configuring Prettier

Let's start by installing the Prettier configuration for ESLint:

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

Now, let's update the .eslintrc.json file to include Prettier:

{
  "extends": ["next/core-web-vitals", "next/typescript", "prettier"]
}

This configuration extends the default Next.js ESLint rules and adds Prettier to avoid conflicts between ESLint and Prettier.

Next, let's create a .prettierrc.json file in the root of your project with the following rules:

{
  "semi": true,
  "singleQuote": false,
  "tabWidth": 2,
  "trailingComma": "es5"
}

These rules set up Prettier to:

  • Use semicolons at the end of statements
  • Use double quotes for strings
  • Set tab width to 2 spaces
  • Use trailing commas in objects and arrays (ES5 compatible)

Configuring ESLint

Now, let's update our .eslintrc.json file with some additional rules:

{
  "extends": ["next/core-web-vitals", "next/typescript", "prettier"],
  "rules": {
    "prefer-arrow-callback": ["error"],
    "prefer-template": ["error"],
    "semi": ["error"],
    "quotes": ["error", "double"]
  }
}

These rules enforce:

  • The use of arrow functions for callbacks
  • The use of template literals instead of string concatenation
  • The use of semicolons
  • The use of double quotes for strings

To see these rules in action, open your layout.js or any other file and try removing semicolons or changing quotes to single quotes. You'll see ESLint highlighting these as errors.

To fix these errors automatically, you can use the VSCode command palette (Cmd+Shift+P on Mac, Ctrl+Shift+P on Windows) and type "ESLint: Fix all auto-fixable problems".

Import Sorting

To automatically sort your imports, we can use the @trivago/prettier-plugin-sort-imports plugin. Install it with:

npm install --save-dev @trivago/prettier-plugin-sort-imports

Now, update your .prettierrc.json file:

{
  "semi": true,
  "singleQuote": false,
  "tabWidth": 2,
  "trailingComma": "es5",
  "importOrder": [
    "^(react|next?/?([a-zA-Z/]*))$",
    "<THIRD_PARTY_MODULES>",
    "^@/(.*)$",
    "^[./]"
  ],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true,
  "plugins": ["@trivago/prettier-plugin-sort-imports"]
}

This configuration sets up import sorting in the following order:

  1. React and Next.js imports
  2. Third-party modules
  3. Absolute imports from your project (starting with @/)
  4. Relative imports

The importOrderSeparation option adds a newline between each import group, and importOrderSortSpecifiers sorts the named imports.

Now, when you run "ESLint: Fix all auto-fixable problems", you'll see your imports being sorted according to these rules. For example, import "./globals.css"; will be moved to the top if you have component imports.

Auto-formatting on Save

To enable auto-formatting on save, create a .vscode folder in your project root, and inside it, create a settings.json file with the following content:

{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "always",
    "source.organizeImports": "always"
  },
  "files.associations": {
    "*.css": "tailwindcss"
  }
}

This configuration:

  • Formats your code on save
  • Runs ESLint fix and organizes imports on save
  • Associates .css files with Tailwind CSS for better IntelliSense

Automatic Class Sorting with Prettier for Tailwind CSS

To enable automatic class sorting for Tailwind CSS, first install the plugin:

npm install -D prettier prettier-plugin-tailwindcss

Then, update your .prettierrc.json file to include the plugin:

{
  "semi": true,
  "singleQuote": false,
  "tabWidth": 2,
  "trailingComma": "es5",
  "importOrder": [
    "^(react|next?/?([a-zA-Z/]*))$",
    "<THIRD_PARTY_MODULES>",
    "^@/(.*)$",
    "^[./]"
  ],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true,
  "plugins": [
    "@trivago/prettier-plugin-sort-imports",
    "prettier-plugin-tailwindcss"
  ]
}

After reloading VSCode, you'll see Tailwind classes being automatically sorted when you save files.

Adding a Format Script

To make it easy to format all files in your project, add a format script to your package.json:

"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start",
  "lint": "next lint",
  "format": "prettier src/ --write"
},

This script allows you to format all files in the src/ directory by running npm run format.

File Naming Conventions

To enforce consistent file naming conventions, we can use the eslint-plugin-check-file plugin. First, install it:

npm i eslint-plugin-check-file

Then, update your .eslintrc.json file:

{
  "extends": ["next/core-web-vitals", "next/typescript", "prettier"],
  "plugins": ["check-file"],
  "rules": {
    "prefer-arrow-callback": ["error"],
    "prefer-template": ["error"],
    "semi": ["error"],
    "quotes": ["error", "double"],
    "check-file/filename-naming-convention": [
      "error",
      {
        "**/*.{ts,tsx}": "KEBAB_CASE"
      },
      {
        "ignoreMiddleExtensions": true
      }
    ],
    "check-file/folder-naming-convention": [
      "error",
      {
        "src/**": "KEBAB_CASE"
      }
    ]
  }
}

This configuration enforces:

  • All .ts and .tsx files to use kebab-case naming
  • All folders under src/ to use kebab-case naming

Conclusion

By following these steps, you've set up a robust Prettier and ESLint configuration for your Next.js project. This setup will help maintain consistent code style, improve code quality, and increase developer productivity. Remember to adjust these configurations to fit your team's specific needs and preferences.