Linting in React
Recently I started experimenting with the idea of code linting via ESLint and Prettier. I recently wrote another article on this subject concerning this Nuxtjs Blog - Webstorm and Nuxtjs Linting. So, enter the story of three tools:
- Prettier: Where as Prettier, is concerned with ensuring "that all outputted code conforms to a consistent style."
- Husky: An NPM package which utilizes GIT hooks to integrate tools and increase quality code submissions to your repository. In addition, using these three together as a
pre-commithook strategy, means all contributors to your project submit with the same code standards.
TLTR: Go to the repository.
To get started create a React App:
yarn create react-app react-linting or
npx create-react-app react-linting. Create React App comes pre-configured with some of the necessary ESLint packages and we need to extend that default configuration. So, we need to install a few additional packages as
yarn add -D eslint-config-prettier eslint-plugin-prettier prettier or
npm install --save-dev eslint-config-prettier eslint-plugin-prettier prettier. These packages will set up the additional linting we require. Since, React uses the
package.jsonfor ESLint configuration, so will I, but you could just as easily is a separate configuration file. Add the prettier plugin to the
eslingConfigsection of the
Instead of a
.prettierrc configuration file we will add a new section to the
package.jsonfile. This section is my configuration but you can change as you desire:
To make these tools more usable, we can add the following to the script section of our
"start": "react-scripts start",
"build": "react-scripts build",
"lint:fix": "eslint src/**/*.js --fix",
"lint": "eslint src/**/*.js",
"prettify": "prettier src/**/*.js --write"
We could stop here, but we are going to automate these task. You need to install two more packages:
yarn add -D husky lint-staged or
npm install --save-dev husky lint-staged. We need to add the following tweo short sections to the
"*.js": "npm run lint:fix"
So now the magic begins. Based on our prettier configuration, change something in a
husky will run
lint-stagedand fix your files automagically. This is just a very basic setup but you get the idea.