loading...
Cover image for Clean ESLint import management for ReactJS

Clean ESLint import management for ReactJS

mjmaix profile image MJ Abadilla ・2 min read

Often times for greenfield projects, we have Prettier and ESLint to do the heavy lifting to organize our codes. It is a common practice today to enforce formatters using Husky and Stage-lint as per this post - Using lint-staged, husky, and pre-commit hooks to fail fast and early.

In doing so, we are investing that our project would be maintainable for a longer time when we invest time to auto-format the code from the start. Keeping aside that we will less be stressed later on after months and we have to refactor parts of the code.

Imports are a mess in JavaScript projects

Working on solo on a ReactJS project doesn't require much attention on code styling and maintenance. You are the only code owner and maintainer.

For many though, we work professionally with ReactJS projects for 5-8 hours a day. When a newly onboarded programmer sees that the code is messy from the start then it puts him into believing that code quality standards are not important to that project, team, and company.

What your new programmer teammate see when first starting to work on a project is the block of imports at the start of every file. This first impressions is very important, it sets the impression that code quality is a first class citizen of the team and he/she will have to maintain the same care the the previous developers have given to the project.

ESLint Plugin Import to the rescue

eslint-plugin-import

ESLint configuration

On your .eslintrc.js add these plugins and rules.

The rules below enforces that:

  1. import React from 'react' is always on top - this is just my personal preference. Remove the pattern: 'react', line to disable.
  2. Imports are ordered by ['builtin', 'external', 'parent', 'sibling', 'index']
  3. Each group will have new lines in-between.
module.exports = {
  plugins: ['import'],
  rules: {
    'import/order': [
      'error',
      {
        alphabetize: {
          order: 'asc',
          caseInsensitive: true,
        },
        'newlines-between': 'always',
        groups: ['builtin', 'external', 'parent', 'sibling', 'index'],
        pathGroups: [
          {
            pattern: 'react',
            group: 'external',
            position: 'before',
          },
        ],
        pathGroupsExcludedImportTypes: ['builtin'],
      },
    ],
  },
};

TODO / Limitations:

The sorting is enforced manually, if you are using VS Code and have the ESlint Plugin then you're good to go. The editor will flag the unordered imports and you'll have the "Quick Fix..." options to sort (though you may have to repeat this multiple times).
Let me know if there is a way to automate this on-save.

linting sample

Discussion

markdown guide