Set up ESLint, Prettier, Commitizen, Husky and friends in 2022
This article is over 4 years old
Published . Tools, APIs and best practices may have moved on since, so some steps or recommendations might no longer apply. Check the linked official documentation for the latest guidance.
A good developer experience when working with a front end javascript project is really important. We're going to look at integratingESLint,Prettier,Commitizen andHusky git hooks (plus a few other things!), to ensure your codebase is consistent and easy to work with. So, grab a cuppa and find your favourite chair, because your development experience will shortly change for the better!
Published:
ESLint is a JavaScript linting tool which can be used to find and fix problems and issues with your code. By default, ESLint enforces some stylistic rules as well as code quality rules, for example semicolon insertion and single- or double-quote marks. ESLint is highly configurable, and individuals or teams can decide at a very granular level which rules to enable or disable.
Prettier, unlike ESLint, is focused purely on code formatting. It isn't just restricted to JavaScript, but can also be used to format HTML, CSS, SCSS, Markdown and more. Unlike ESLint, Prettier is opinionated about the formatting that it does, which means there are far fewer configuration options to choose from, or argue about as a team.
Husky is a great tool for configuring Git hooks, which can automatically lint code and commit messages, run unit tests (and so much more) before you push or commit to a remote repository. This helps to ensure no bad code gets into the repository because someone forgot to manually run the lint or test commands first!
Finally, Commitizen is a tool that is useful in helping to ensure that Git commit messages are formatted in a consistent way. An interactive prompt will guide you through authoring the commit message. We'll use the cz-conventional-changelog adapter, which follows the conventional-changelog format (although there are others to choose from).
Getting started
In a new workspace, use npm init to generate apackage.json file, accepting the defaults unless you want to change anything.
{
"name": "my-soon-to-be-pleasurable-to-work-with-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}Set up ESLint and Prettier
Now that our package.json is created, we'll install ESLint and Prettier. We also useeslint-config-prettier, which helps de-conflict Prettier and ESLint by turning off ESLint rules that are unnecessary or might conflict with Prettier. These three tools should all be installed as development dependencies.
npm install eslint prettier eslint-config-prettier --save-devAt the time of writing, the versions installed were:
prettier2.5.1.eslint-config-prettier8.3.0.eslint8.8.0.
Create an ESLint configuration file
The ESLint configuration file is used to configure ESLint. ESLint provides a handy tool to generate the configuration file:
npm init @eslint/configSelect “To check syntax and find problems”, and choose JSON for the configuration format. The other options can be set to suit your project. The generated configuration may look different from the example below, depending on your choices.
{
"env": {
"browser": true,
"commonjs": true,
"es2021": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": "latest"
},
"rules": {}
}Create Prettier configuration and ignore files
Create a .prettierrc file in the project root. This lets editors and other tools know that we're using Prettier.
The example sets the tab width to four spaces. Other Prettier configuration options are available in the Prettier documentation.
{
"tabWidth": 4
}Create a .prettierignore file in the project root too. This tells the Prettier CLI and extension which files and directories not to format.
# Ignore artifacts:
package-lock.json
build
coverageDeconflict ESLint and Prettier rules
Since we installed eslint-config-prettier, add Prettier to the extends array in .eslintrc.json. Keep it last so it can override other configurations.
{
"env": {
...
},
"extends": ["eslint:recommended", "prettier"],
"parserOptions": {
...
},
"rules": {
...
}
}eslint-config-prettier includes a CLI tool that identifies ESLint rules conflicting with Prettier. This is particularly helpful when adding Prettier to an existing ESLint project. Run the following command and manually turn off conflicting rules in the ESLint rules array if necessary.
npx eslint-config-prettier path/to/main.jsTesting ESLint and Prettier
Check whether the project conforms to ESLint and Prettier rules:
npx eslint . // run ESLint on all files
npx prettier --check . // check formatting
npx prettier --write . // format and fix filesAdding helper scripts to package.json
These commands can also be added to the scripts inpackage.json:
{
...
"scripts": {
"prettier:check": "npx prettier --check .",
"prettier:fix": "npx prettier --write .",
"lint": "npx eslint ."
...
}
}Add extensions to VSCode (optional)
If using VS Code, install theESLint extensionandPrettier - Code Formatter. Set your default formatter to Prettier and enable Format On Save to have files reformatted automatically when saved.
These extensions can also be recommended to other contributors through.vscode/extensions.json, prompting them to install the same tools when they open the project.
{
"recommendations": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode"
]
}Recommended extensions don't prevent developers from committing without linting and formatting code, or from writing unclear commit messages. The next section uses Husky hooks to run these checks automatically before committing.
Configuring Husky and lint-staged to lint and format code before commit
Setting up Husky
Husky configures Git hooks, which can automatically lint code and commit messages or run tests before Git actions take place. Its one-time setup command quickly adds Husky to a codebase:
npx husky-init && npm install --save-devAt the time of writing, this command installed Husky version 7.0.4.
Running it adds a .husky directory with a sample pre-commit hook and modifies package.json with a prepare script. This ensures Husky hooks are installed when a local npm installruns or before the package is published.
The generated .husky/pre-commit hook runsnpm test before committing. If tests fail, the commit is aborted.
Setting up lint-staged
lint-staged limits linting to staged files for performance, which is useful when adding ESLint and Prettier to an existing codebase.
npm install lint-staged --save-devAt the time of writing, lint-staged version 12.3.3 was current.
There are several ways to configure lint-staged, such as a.lintstagedrc file or lint-staged.config.js. You can also add a lint-staged object topackage.json:
{
...
"lint-staged": {
"*.{css,less,scss,html,json,jsx,js}": [
"prettier --write ."
],
"*.js": "eslint --fix"
}
}This configuration runs Prettier against the selected staged file types and ESLint against staged JavaScript files. The --write flag automatically fixes formatting issues that Prettier finds, and--fix lets ESLint automatically fix supported issues.
Wire up the Husky pre-commit hook to call lint-staged by updating.husky/pre-commit:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-stagedRun npm install so Husky can pick up the new hooks. After this, ESLint errors and Prettier formatting issues in staged files will be checked and automatically fixed where possible before the commit task runs.
Set up Commitizen and friends
We're now going to add Commitizen to the project. With the help ofcommitlint, we can enforce standardised commit messages.
Install the following packages:
- Commitizen, for writing conventional commit messages in a CLI tool.
- The cz-conventional-changelog adapter, which enforces the conventional changelog commit format.
@commitlint/cliand@commitlint/config-conventional, which lint commit messages.
Install Commitizen, cz-conventional-changelog, lint-staged and @commitlint
Install the packages with this command:
npm install commitizen cz-conventional-changelog @commitlint/cli @commitlint/config-conventional --save-devAt the time of writing, the package versions were:
commitizen4.2.4.cz-conventional-changelog3.3.0.@commitlint/cli16.1.0.@commitlint/config-conventional16.0.0.
Commitizen configuration
Add a config.commitizen key to the root ofpackage.json. This tells Commitizen which adapter to use when committing. Alternatively, store this configuration in a.czrc file to keep package.json clean.
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
},
...
},Commitlint configuration
Add a commitlint.config.js file to the project root. This works similarly to ESLint configuration. Here it extends@commitlint/config-conventional, though you could override rules if needed.
module.exports = { extends: ["@commitlint/config-conventional"] };Commitlint configuration can also be defined in.commitlintrc.js, .commitlintrc,.commitlintrc.json, .commitlintrc.yml, or acommitlint field in package.json.
Husky hook creation
Husky helps enforce a consistent commit format for contributors. In the.husky folder, add a prepare-commit-msg hook:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
exec < /dev/tty && npx cz --hook || trueWhen running git commit, this launches an interactive Commitizen session to guide the user through writing a meaningful message. Add a commit-msg hook to run commitlint after the message is entered:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx commitlint --edit $1To test the hooks, change a file and try committing with a non-conventional commit message:
git add .
git commit -m "I'm a cowboy"After lint-staged runs, the interactive Commitizen CLI launches to help write a message that meets the requirements. In VS Code source control, an invalid message should fail, and the integrated terminal will show why it wasn't accepted.
Wrap up and demo
With these tools configured, we can stop bad code making its way into the repository and enforce standards for consistency across our own projects and projects with multiple contributors.