Using Husky, ESLint, or Prettier, to automatically format your code

Jul 14, 2022by, Amalendhu K R

Technology

Any software engineer working on a project with other developers must maintain a consistent code style. It vastly improves the readability and maintainability of the code.Let’s figure out how to automate this critical process every time someone commits.

  • Install packages
  •  Husky- allows you to run custom scripts against your repository. Here, we deal with the pre-commit git hook.
  • ESLint- is a so-called linter, a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code.
  • Prettier- is a code formatted
  • Lint-staged- is used to run linters against staged git files. Linting ensures no errors go into the repository and enforce code style.
npm install --save-dev eslint prettier lint-staged husky
  • Configure ESLint
Initialize ESLint by creating .eslintrc, a special configuration file. Basic configuration contains:
{
"extends": ["eslint:recommended", "react-app", "react-app/jest"],
"rules": {
"no-console": "off"
}
}

We must modify the ESLint configuration to include the information that we will also be using Prettier. Install prettier specific ESLint config:

npm install --save-dev eslint-config-prettier
Make respective changes in the package.json
{
/* other configurations */
"eslintConfig": {
"extends": [
"eslint:recommended",
"react-app",
"react-app/jest",
"prettier"
],
/* other configurations */
}
}

We can add our own set of rules to the overrides section (if we want it to be applicable to the whole project) or the configuration rules section (if it’s only intended to function with a specific set of files). The linter will react to the code fragments coming under it based on one of the three predicted values listed below:
– 0 or “off” – the rule will not be active,
– 1 or “warn” – the linter will provide a warning as response,
– 2 or “error” – the linter will issue an error as response and stop compilation
For example, “no-console”: 2 will abort the compilation of application (an error will be thrown) immediately after the linter finds console.log


{
"eslintConfig": {
"extends": [
"eslint:recommended",
"react-app",
"react-app/jest",
"prettier"
],
"rules": {
"no-console": 2
}
}

You can check out all the available configurations on the official documentation.

We can run the linter independently whenever needed. The easiest way is to just include the necessary script to the package.json file:

{
(...)
"scripts": {
(...)
"lint": "eslint --fix './src/**/*.{js,jsx}'"
}
(...)
}
And run it with the command:
npm run lint

The npx tool is another option to run the lint separately,

npx eslint --fix './src/**/*.{js,jsx}

 

  • Configure Prettier

Add a .prettierrc.json file to your project root and use the below code as a starting point:

{
"bracketSpacing": true,
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 2
}

In this example, Prettier formats the code by giving spacing between brackets, adding semi-colons wherever needed, accepting the single-quotation marks to format the strings, providing trailing commas wherever acceptable (objects, arrays, functional parameters and calls , etc.), changing the length of printers to 80 and providing indentation with a level of 2.

Visit Prettier Documentation to check out all the available configuration options.

You can add a .prettierignore file to ignore files from formatting, use the below code as base:

package-lock.json
yarn.lock
node_modules
# any other unwanted files or folders

As with linter, we can run Prettier independently in two ways:
One is through adding a script in package.json file,

{
(...)
"scripts": {
"prettier" : "prettier --write ."
}
(...)
}

And running it with,

npm run prettier

The second way is as usual by the npx tool,

npx prettier -write
  • Configure Lint-staged

Lint-staged too is very easy to configure. Add the following script to your package.json file:

{
/* other configurations */
"lint-staged": {
"**/*.{js,jsx}": ["eslint . --fix", "prettier --write ."]
}
}

A glob pattern-defined subset of all staged files is what linter commands operate on. Here,
“**/*.{js,jsx}” will match all JS and JSX files, for example /test.js, /test.jsx, /component/abc/test2.jsx, etc.

Multiple commands can be run by passing those commands as an array on every glob. The above code will execute prettier -write on all staged **/*.{js,jsx} files only after exiting the eslint execution with 0 code. Some of the errors the linter finds will be fixed automatically due to the -fix flag.

  • Configure Husky

The following script must be added to package.json to configure husky:

{
/* other configurations */
"scripts": {
/* other scripts */
"configure-husky": "npx husky install && npx husky add .husky/pre-commit \"npx --no-install lint-staged\""
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
}
}

Run the configure-husky script to install Husky and connect it to the pre-commit hook:

npm run configure-husky

Let’s try committing some changes

BINGO! IT WORKS!

 

Disclaimer: The opinions expressed in this article are those of the author(s) and do not necessarily reflect the positions of Dexlock.