DEV Community

Cover image for Standardize imports with ESLint
Jesús Mejías Leiva for Product Hackers

Posted on • Updated on • Originally published at blog.susomejias.dev

Standardize imports with ESLint

Adding this configuration will significantly improve the readability of our imports since they will follow a standard which we will define in said rule, let's see some small examples.


Requirements

In this article it will be assumed that ESLint is already configured in the project, if you do not have any configuration you must follow the official documentation that I attach here: ESLint configuring.

We will also need to install the following library with npm or yarn:

Npm:

npm install eslint-plugin-import --save-dev
Enter fullscreen mode Exit fullscreen mode

Yarn:

yarn add -D eslint-plugin-import
Enter fullscreen mode Exit fullscreen mode

Imports without rule 🤨

As can be seen, the ordering and grouping that is followed does not follow any criteria and what is even worse is that in other files they will follow different or even opposite criteria.

import React from 'react'
import AnotherComponent from './AnotherComponent'
import dayjs from 'dayjs';
import styles from './styles.module.scss'
import _ from 'lodash';
Enter fullscreen mode Exit fullscreen mode

ESLint to rescue 🛟

Within our ESLint configuration file we will add the following rule, in this example I will use a configuration of my preference, if you need more information I will leave you here a link to the official documentation.

{
  "import/order": [
    "error",
    {
      "newlines-between": "always",
      "groups": [
        ["builtin"],
        ["external"],
        ["parent", "internal", "sibling", "index", "unknown"]
      ],
      "alphabetize": {
        "order": "asc",
        "caseInsensitive": true
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

It is important to note that to fix all the "errors" in existing imports that this rule will cause, it is recommended to use the --fix flag to automate the resolution of said "errors".


Imports with rule 🥰

We can see that everything is much more readable since with a simple glance we will be able to identify the imports of external and internal packages that are used in said file and the best thing is that in this way we unify criteria in all the imports of our application.

import dayjs from "dayjs";
import _ from "lodash";
import React from 'react'

import AnotherComponent from './AnotherComponent'
import styles from './styles.module.scss'
Enter fullscreen mode Exit fullscreen mode

You can see more complex examples here.


Conclusions

As we have seen, adding this rule gives us a very good cost vs benefit since with a very basic configuration we obtain the great benefit of being able to have a standard in all the imports of our project, something that is really useful if you work with several people.


Thanks for reading me 😊

Top comments (0)