ESLint
We'll use ESLint (opens in a new tab) to statically analyze our code for potential errors. Note that we will not be using ESLint in one way that it's commonly used, to check adherence to a particular set of style guidlines. Instead, we'll be using Prettier to automatically format our code in a consistent way as we go.
The way we created our project with create-next-app
already did an initial
setup of ESLint, but we'll modify a few things.
Moving Configuration
First, in alignment with our principle around centralizing configuration, we'll move the contents
of the automatically created .eslintrc.json
file into the eslintConfig
section of our
package.json
:
"eslintConfig": {
"extends": [
"next/core-web-vitals",
]
}
Adding Recommended Rules
We also want to include ESLint checks for all of its recommended rules (opens in a new tab). But, to avoid conflicts with our TypeScript setup, we'll need to use the typescript-eslint (opens in a new tab) project.
We'll follow its installation instructions (opens in a new tab), adapting
them to keep our configuration in package.json
:
- Install the necessary packages:
npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin
- Update the
eslintConfig
section of ourpackage.json
to use thetypescript-eslint
plugin, parser, and ruleset:
"eslintConfig": {
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"next/core-web-vitals"
],
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
]
}
Running Manually
Now, we can run npm run lint
to have ESLint check our code. Fortunately, there are no issues!
✔ No ESLint warnings or errors
Wouldn't we have gotten the same results running npm run lint
before that
additional configuration?
npm run lint
before that
additional configuration?Yes, but that's because the code created by create-next-app
doesn't have
any issues that violate the rules from the additional ESLint packages we
installed. To see an example that does, add an unused variable to your
layout.tsx
file, like this:
import './globals.css'
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
const x = 0;
export const metadata: Metadata = {
// rest of layout.tsx
Now, when you run npm run lint
, you'll see the following error:
./src/app/layout.tsx
7:7 Error: 'x' is assigned a value but never used. @typescript-eslint/no-unused-vars
info - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules
That issue wouldn't have been caught before we added the eslint:recommended
ruleset.
VS Code Integration
TODO
(3 (opens in a new tab)): VS Code Integration for ESLint