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.

ESLint Rules

This is the GitHub project I got with these ESLint rules added:

Sort Imports

Even though ESLint has this sort-imports rule (; however, --fix will not reorder automatically for multiple lines.

However, we could use library eslint-plugin-import that allows --fix. To install:

Add the below line to your .eslintrc file:

.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.

ESLint extension in Virtual Studio Code
ESLint Errors for imports

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:

Run script lint:fix

Audit Accessibility

To audit accessibility with linting, we could use library eslint-plugin-jsx-a11y:

Add the below lines to your .eslintrc file:

Now the code editor could pick up the linting errors related to accessibility:

Linting errors for accessibility

We could also use unit testing to check accessibility as well. We could use the library jest-axe:

To set it up, create a file called jest.setup.js with below content:

Specify this file as setup file in your jest configure file (jest.config.js, or jest.config.ts):

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:

In package.json, you could add pre-commit and pre-push commands similar to below:

Now you do a git commit or a git push, the hooks command will run.

Git Commit will trigger husky pre-commit

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 ✌️🏼~

A frontend web developer in Toronto