Add ESLint Rules to Sort Imports And Audit Accessibility

  • add ESLint rules
  • add scripts in package.json
  • add pre-commit hooks
ESLint Rules

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.

# 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:

.eslintrc file
ESLint extension in Virtual Studio Code
ESLint Errors for imports

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",
Run script lint: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
Linting errors for 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
import { toHaveNoViolations } from 'jest-axe'; expect.extend(toHaveNoViolations);
setupFilesAfterEnv: ['./jest.setup.js']

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
"husky": {
"hooks": {
"pre-commit": "npm run lint",
"pre-push": "npm run lint && npm test"
}
}
Git Commit will trigger husky pre-commit

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Emily Xiong

Emily Xiong

A frontend web developer in Toronto