Add ESLint Rules to Sort Imports And Audit Accessibility
Adding ESLint rules to sort imports statements and audit accessibility will ensure code consistency across the team and catch some errors early.
This blog shows how to:
- add ESLint rules
- add scripts in package.json
- add pre-commit hooks
It assumes that your project already has ESLint installed.
This is the GitHub project I got with these ESLint rules added: https://github.com/xiongemi/white-label-airline.
Sort Imports
Install
Even though ESLint has this sort-imports
rule (https://eslint.org/docs/rules/sort-imports); however, --fix
will not reorder automatically for multiple lines.
However, we could use library eslint-plugin-import that allows --fix
. To install:
# npm
npm install eslint-plugin-import --save-dev# yarn
yarn add eslint-plugin-import --dev
Add Rules
Add the below line to your .eslintrc
file:
If you are using Visual Studio Code and have ESLint extension installed, in the code editor, the linting errors for imports that are not ordered should show up.
Add Script to package.json
Now using eslint --fix
should automatically sort the imports statement. You could add that script to your package.json. For example, the below script will automatically sort import statements for files with ts
and tsx
under apps folder:
"lint:fix": "eslint \"./apps/**/*.{ts,tsx}\" --fix",
Audit Accessibility
Linting
To audit accessibility with linting, we could use library eslint-plugin-jsx-a11y:
# npm
npm install eslint-plugin-jsx-a11y --save-dev# yarn
yarn add eslint-plugin-jsx-a11y --dev
Add the below lines to your .eslintrc
file:
Now the code editor could pick up the linting errors related to accessibility:
Unit Testing
We could also use unit testing to check accessibility as well. We could use the library jest-axe
:
# npm
npm install jest-axe --save-dev# yarn
yarn add jest-axe --dev
To set it up, create a file called jest.setup.js
with below content:
import { toHaveNoViolations } from 'jest-axe'; expect.extend(toHaveNoViolations);
Specify this file as setup file in your jest configure file (jest.config.js
, or jest.config.ts
):
setupFilesAfterEnv: ['./jest.setup.js']
This is a unit test to check accessibility violation for a React component:
Pre-commit Hooks
Now with all these linting rules and unit tests in place, we need to enforce them with pre-commit hooks. We need to install husky:
# npm
npm install husky --save-dev# yarn
yarn add husky --dev
In package.json, you could add pre-commit and pre-push commands similar to below:
"husky": {
"hooks": {
"pre-commit": "npm run lint",
"pre-push": "npm run lint && npm test"
}
}
Now you do a git commit or a git push, the hooks command will run.
Now with all these ESLint rules added and enforced, it is going to be beneficial for the project in a long run.
Happy linting and unit testing ✌️🏼~