React 102 : Configuring code formatting using Prettier, ESLint & Husky
In this article I’ll be diving into setting up pettier, eslint and husky for configuting the code formatting rules for your react js application. I will be using yarn as my package manager.
First ensure you have node and yarn installed. You can do this by following this tutorial : https://medium.com/@rimazmohommed523/react-101-creating-your-starter-react-app-using-yarn-berry-yarn-3-3-1-e40ed98ec14
Create your React App
Next we will be creating the our app using the create react-app command : https://create-react-app.dev/docs/getting-started
- yarn create react-app <your-app-name>
Once the installation is complete, change dir into your app, and run yarn start
and ensure your app runs without any errors
App running on localhost:3000
Configure Prettier
I will be using VS Code as my IDE. So as a prequisite, ensure you have installed the prettier vs code plugin in the extensions left menu.
You can also install it by pressint Ctrl+P and running `ext install esbenp.prettier-vscode`
Now install prettier using yarn yarn add --dev --exact prettier
We install prettier as a dev dependency and we also save exact to ensure that everyone working on the project gets the exact same version of Prettier, as different versions can sometimes give us different formatting.
Next lets create a .prettierrc.json
file to configure our code formatting rules and also add a script to format our code using prettier
Create a .prettierrc.json file in the root of your app and add the following rules
{
"semi": false,
"tabWidth": 2,
"printWidth": 100,
"singleQuote": true,
"trailingComma": "all",
"jsxSingleQuote": true,
"bracketSpacing": true
}
Now lets add a yarn script to format our code using the terminal
"format": "prettier --write src/**/*.{js,jsx,ts,tsx,css,md,json,scss} --config ./.prettierrc.json"
You can now run yarn format
to format your code to use your prettier config.
You will notice that after running yarn format
your code was updated to conform to the prettier config you defined in your .prettierrc.json
file.
App.js before formatting your code using prettier
App.js after running yarn format
. Notice how the semi-colons were removed since you have configured your .prettierrc.json
to have "semi": false
.
Finally lets configure VS Code to run your prettier formatting rules on save. To do this, first create a .vscode
dir in the root of your application. Then create a settings.json
file and add the following:
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.formatOnPaste": false
}
You can validate that this works by writing some code and press Ctrl+S to save. You will notice that the prettier rules will run on save and update the code to conform to the config.
You can also create a .prettierignore file to ignore any files or dirs that you do not want prettier to format. See : https://prettier.io/docs/en/ignore.html. By default prettier ignores files in version control systems directories (“.git”, “.svn” and “.hg”) and node_modules.
We don’t really need this cause yarn format
is set to only format files inside the src
dir. However having this is still good as it will prevent artifacts and the public dir etc. getting formatted incase someone directly runs prettier in your code like: yarn run prettier --write .
Configure ESLint
Although Prettier is an awesome code formatting tool, it doesn’t understand what the code does. So for example a const that is declared but never used is not raised as an issue. But ESLint understands the meaning of code using static analysis and detects problems.
Lets start by installing the ESLint plugin in VS Code if you haven’t already got it.
Now lets run the following code to configure ESLint for our app :
npx eslint --init
For the first question on how you are planning to use eslint, select the last option of checking syntax, problems and enforcing code styles.
Next select Javascript modules for the type of modules.
For the framework, select React
I’m not using typescript, so I’ll be answering No
for the next question
For the question on where your code runs, select Browser
For code style, choose Use a popular style guide
And we will be sticking with the Standard style guide. Read more here : https://github.com/standard/eslint-config-standard. Also this is a good article comparing the common style guides : https://betterprogramming.pub/comparing-the-top-three-style-guides-and-setting-them-up-with-eslint-98ea0d2fc5b7
Select JSON
as the config file format
Finally select your package manager. I’m using Yarn
Next lets also install the eslint-config-prettier library so that we can extend eslint rules from our prettier config and ensure there are no conflicts between the two.
yarn add -D eslint-config-prettier
We can now configure our .eslintrc.json
file. I’ve configured mine like so :
{
"env": {
"browser": true,
"es2021": true
},
"extends": ["plugin:react/recommended", "standard", "prettier"],
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": ["react"],
"rules": {
"quotes": ["error", "single"]
},
"settings": {
"react": {
"version": "detect"
}
}
}
I’ve also added the following scripts for linting using my yarn package manager. Once again I’m targeting only the src
dir.
"lint": "eslint src/**/*.{js,jsx,ts,tsx,json}",
"lint:fix": "eslint --fix src/**/*.{js,jsx,ts,tsx,json}"
If you try running yarn lint
now. You will see some linting errors popping up. I’ve tried also running yarn lint:fix
but unfortunately most linting errors aren’t auto fixable so we will have to fix these manually
To fix the JSX issue, in App.js and App.test.js make sure you add the following import React from 'react'
And to fix the Jest error add the following comment to the file :
- /* eslint-env jest */
Running yarn lint
will show no lint errors exist
Lets now create a .eslintignore
file similar to what we did with prettier and ignore dirs we don’t want the linter to run on. You can add to this file if you ever come accross files or dirs you do not want linted. See : https://eslint.org/docs/latest/use/configure/ignore
Configure Husky
So far we’ve configured prettier and eslint and its all great. But it would be awesome if we can also run our code formatter and linter whenever we commit our code using a git hook and prevent someone from committing code if the linter shows up with any errors.
To do this, we will install husky
and lint-staged
- yarn add -D husky lint-staged
Then update package.json
to and alint-staged
section. Configuration should be an object where each value is a command to run and its key is a glob pattern to use for this command. This package uses micromatch for glob patterns. See : https://github.com/okonet/lint-staged#readme
"lint-staged": {
"src/**/*.{js,jsx,ts,tsx,css,md,json,scss}": [
"yarn format"
],
"src/**/*.{js,jsx,ts,tsx,json}": [
"yarn lint"
]
}
Now we need to configure husky to call lint-staged. For that, run the following script :
- npx husky-init && yarn install
Once done, update the husky pre-commit file to run yarn lint-staged
Now lets Test that the pre-commit hook works. Lets add a line in App.js that breaks the linter. Ex : const myBadVar = 10
. You can see the variable is already highlighted as a linter error by VS Code. Nevertheless, lets save it.
Now run git add
and then git commit -m "add my bad var"
. You can see the husky hook works and lint-staged is run and the linter error is thrown.
Now lets fix it and re-run.
You can see the formatting happened, and the linter passed.
We are all good!