Linters are so useful that when we end up in a project without one, we are totally frustrated. It happened to me with this very project and we will see how to set up a linter and leverage huge time benefits.
Basic Next.js linter
The default Next.js linter isn't installed automatically, and we get noticed every time we build our application.
Following Next.js advice, we run yarn lint
in the terminal to face another error. We must first install it.
I had issues installing the linter with npm
, so I will use yarn in this article, as advised by the Next team.
- Install ESLint
yarn add --dev eslint
- Run lint
yarn lint
- Follow the instructions to install
strict
orbase
Next.js linter - Run
yarn lint
again and this time it will scan the entire app and give back the potential linter errors - If there are errors,
yarn lint --fix
will fix everything automatically, but there is also a log of every error and their location to solve manually
Extend the linter rules
Would we have more rules to our linter, there is a way to extend what Next.js set as linting.
- We should have a
.eslintrc.json
file to open Strict:
{
"extends": "next/core-web-vitals"
}
Basic:
{
"extends": "next"
}
- We make the
extends
an array of strings and add anything, for exampleeslint-config-airbnb
{
"extends": ["next/core-web-vitals", "eslint-config-airbnb"]
}
- Install it with the command
yarn add --dev eslint-config-airbnb
- If we want to change any linter rule, here is the way
{
"extends": ["next/core-web-vitals", "eslint-config-airbnb"],
"rules": {
"react/no-unescaped-entities": "off",
"@next/next/no-img-element": "off"
}
}
- We can check this official link for more info on linters
Format on save with Prettier
Another point I find close to linters are the formatters. They help us to have consistent syntax and spaces across all our files. Let's see how their magic can happen on every save.
- Install Prettier
yarn add --dev prettier eslint-config-prettier
- If there isn't one already, we create a
.prettierrc.json
file - Here are my usual settings:
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"tabWidth": 2,
"useTabs": false
}
- Check out all settings available
- There is also a
.prettierignore
file to avoid formatting some files - Let's go to the editor settings and update 'default formatter' to Prettier
- Let's save any file to see the magic happen
We are all set to code efficiently with the help of linters and formatters.
Enjoy coding with Next.js!