So, linters! What are they? Why? and how to set up in NextJS
Hi there, reader. Have you ever heard of linters? In this article, I write about three linters, EsLint, Prettier, and Husky. Describe them in context, explaining their purpose, showing you how to set them up in your react environment project, and configuring them to work best for you.
Prerequisite
To get the most out of this article, it would only be fair for me to point out the following assumptions;
What are linters?
Linters are tools that analyze your source code to find and identify potential errors, stylistic issues, and other problems. They help ensure code quality, maintainability, and adherence to coding standards. The primary purpose of a linter is to catch issues early in the development process, reducing the likelihood of bugs, improving code consistency, and making code reviews more effective.
Some key aspects of linters include:
Error detection, code style and checking, best practices, code complexities, security and customization.
ESLint
This is a JavaScript-based linter that helps set or define rules to follow as you write your JavaScript code. In simple terms, ESLint makes suggestions for you to avoid bugs, follow a certain convention, clean up unnecessary logs, or adhere to some best practices. I chose to use ‘some” because it allows you to set up your project to execute checks at runtime, after pasting, after saving, after building, or under specific conditions that you define.
ESLint rules can be found here.
However, some of the issues that ESLint finds can be automatically fixed, we will later configure ESLint to fix everything it can figure out by itself whenever we hit save.
Install ESLint
npm install eslint --save-dev
The flag ‘save-dev’ in npm (Node Package Manager) is used to save packages as development dependencies and that wont necessarily be needing in production.
Configure ESLint
npx eslint --init
Attached below is a screenshot of the settings that I chose for this project, feel free to choose your preferred settings or customize your own configurations.
Let’s review the given prompts and discuss what just happened.
ESLint asks you to provide context on your project setup so that it can install the required packages to meet your project needs.
The config command also creates a .eslintrc.js file. ESlint will find eslintrc* files and use them to enforce the rules that you specify in the file.
On this file, you can also modify, set, or disable some of the rules extended from Google’s linting rules.
I am using JavaScript in my setup, and since I’ll also be integrating MUI, I would like to use the Google Style Guide for my code, with the code served through a web browser.
Prettier
There could be a chance that you already have used this linter. Writing this article was inspired by a tweet I made when I first learned how to configure prettier.
Prettier is an opinionated code formatter.
It removes all original styling and ensures that all outputted code conforms to a consistent style.
In JavaScript, this linter will do things like adding a semicolon to the end of every statement, refactoring your indentation, and ensuring your code structure is consistent on every file.
Install prettier
npm install --save-dev --save-exact prettier
Additionally, we need an eslint-config-prettier package, to prevent format conflicts between ESLint and prettier. It disables all ESLint rules that are unnecessary or those that might conflict with prettier.
npm install --save-dev eslint-config-prettier
Add “prettier” to the extends array in your eslintrc.js file to make prettier cooperate with ESLint to appear as shown
extends: [ 'google', 'plugin:react/recommended', 'plugin:prettier/recommended', 'prettier' ]
To give it the ability to override other configurations, make sure you place it last. Create a.prettierrc file in the project’s root directory to further configure Prettier.
I added these configurations to the .prettierc file as shown below.
{
"bracketSpacing": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"endOfLine": "auto"
}
Addons: .prettierignore and .eslintignore
We can set up ESLint and Prettier to avoid formatting or linting specific files or folders, just like with .gitignore.
I have this code on both .prettierignore and .eslintignore files:
node_modules
/.next/
/build
.next
next-env.d.ts
yarn.lock
public
package-lock.json
Setup prettier and ESLint in Visual Studio
Install Extension
There are extensions for Prettier and ESLint inside Visual Studio Code. Install these two extensions on your system. To launch the extension window, use Ctrl + Shift + X on your keyboard.
Preference
Go to File > Preference > settings to adjust these extensions at the user level.
Search “default formatter” in the search bar, under the Editor: Default Formatter set it to Prettier — code formatter.
Next, search “Format on “ in the search bar and tick Editor: both format on paste and format on save.
For my setup, I have ‘autosave’ enabled as a result prettier will always format when VSCode saves my code.
To ensure everything works, go to index.js on your keyboard, hit Ctrl + Shift + I, or right-click within the file and select format document from the menu options.
As displayed above, you might get prompted to select an alternative; choose prettier.
Your code should be formatted automatically if everything is correct. Moreover, you might have to restart VS Code.
If you are following along, ESLint will have a few things to shout about our page.js file.
Not to worry, all that it’s saying is that we need to make a few changes:
- Strings must use single quotes
- React mus be in scope when using JSX
- JSX not allowed in files with extension .js
Either update manually or alternatively hover your cursor on the error line, select quick fix then choose an option to address the error.
Format on save
I’ve tweaked the VS Code settings even further to allow formatting on save, and to allow ESLint to apply auto-fixable issues.
- Create a .vscode folder at the root of your directory
- Within this folder create a settings.json file
- Add the code from the snippet below
{
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.fixAll.format": true
}
}
Husky
Husky is a linter that runs code checks on git commit. It is merely a filter to evaluate whether the modifications align with both prettier and ESLint.
Every time we push staged changes, husky will ensure that::
- Alert in case of any prettier and or Eslint warning on our code
- Check no errors are compiling out code
- Check we can build our project using the next build command
Install husky
npx husky-init
then run
npm install
This command will updated package.json and create a sample pre-commit hook that we can modify. Below is a preview of the updated package.json
"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 --ext jsx",
"format": "prettier --write .",
"prepare": "husky install"
},
Summary, additional commands were updated on the scripts block as shown above.
check-format command instructs prettier to check all our files excluding the ones in .prettierignore for formatting issues.
check-lint command instructs ESLint to check for any linting warnings/errors on .js and .jsx files that also applies to typescript files.
format tells prettier to automatically re-write all file with proper formatting.
One last flex.
Editing the pre-commit hook
This hook is executed before a git commit is made. When we first initialized Husky, it was generated. To put it in perspective, when you use the git commit command, this hook will run first, and if it is successful, a commit will be carried out. The commit does not proceed if the pre commit hook fails.
Here is my modified pre-commit message and tests
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged
echo '🏗️👷 Styling, testing and checking your code before committing'
# Check Prettier standars
npm run check-format || (
echo '🤢🤮🤢🤮 Your code format/styling seems out of our scope 🤢🤮🤢🤮
Prettier Check Failed. Run npm run format, add changes and try commit again';
false;
)
# Check ESLint Standards
npm run check-lint ||
(
echo '😤🏀👋😤 Get that weak stuff out of here! 😤🏀👋😤
ESLint Check Failed. Make the required changes listed above, add changes and try to commit again.'
false;
)
# If everything passes... Now we can commit
echo '✅✅✅✅ You win this time... I am committing this now. ✅✅✅✅'
As you can see, I enjoy a little humor in my messages. To put it briefly, this file says the following before a commit:
- Check Prettier standards looks good (otherwise fail commit)
- Check ESLint standards looks good (otherwise fail commit)
Conclusion
There are more linters but I got us started on these three for they have really have improved my developer experience.
Checkout other linters:
- Storybook
- CSS: stylelint
- Ruby: rubocop
- Java: checkstyle
- Python: pylint
Thanks for reading!