DEV Community

Cover image for Sorting your imports with ESLint
Julio Xavier
Julio Xavier

Posted on

Sorting your imports with ESLint

On files that use a lot of resources, imports can become a mess. Enforcing styles and patterns can be helpful, however, doing that manually doesn't seem to be the best use of time.

Fortunately, nowadays there are some amazing tools out there that can help us keep our imports organized automatically.

For this article, we will be using eslint-plugin-simple-import-sort. This is an ESLint plugin that enables not only sorting with some nice defaults but also grouping based on defined patterns.

The target

Let's take for the following code:

// an import using an alias path
import { Header, Card } from 'components';
// an import from a package that we want to always see first
import React, { useState } from 'react';
// an ui package
import { Button } from 'ui-package';
// a relative import that is in the same folder
import { parseTableData } from './utils';
// a relative import that is up in the tree
import { generatePath } from '../../domain';
Enter fullscreen mode Exit fullscreen mode

The organization we would like to enforce is:

  • The "react" import should always come first
  • Package imports should come next, sorted by alphabetical order
  • The named imports should be sorted in alphabetical order
  • It should skip a line before relative imports that are in other folders
  • It should skip a line before the imports that are in the current folder

Set up

To set up the plugin, first, it's needed to have ESLint integrated into your project.

The first step is installing the plugin:

yarn install eslint-plugin-simple-import-sort
Enter fullscreen mode Exit fullscreen mode

Then, in your ESLint config file (.eslintrc.json) add the plugin in the "plugins" list.

# eslintrc.json

{
  "plugins": ["react", "simple-import-sort"], 
  "rules": {
    // increase the severity of rules so they are auto-fixable
    "simple-import-sort/imports": "error",
    "simple-import-sort/exports": "error"
  }
}
Enter fullscreen mode Exit fullscreen mode

This should be enough to sort the paths and the named exports alphabetically.

One step further

Now, going one step further. It's also possible to set custom groupings, so it skips lines before sets of imports.

In the ESLint config file, add the following override:

{
  "overrides": [
    // override "simple-import-sort" config
    {
      "files": ["*.js", "*.jsx", "*.ts", "*.tsx"],
      "rules": {
        "simple-import-sort/imports": [
          "error",
          {
            "groups": [
              // Packages `react` related packages come first.
              ["^react", "^@?\\w"],
              // Internal packages.
              ["^(@|components)(/.*|$)"],
              // Side effect imports.
              ["^\\u0000"],
              // Parent imports. Put `..` last.
              ["^\\.\\.(?!/?$)", "^\\.\\./?$"],
              // Other relative imports. Put same-folder imports and `.` last.
              ["^\\./(?=.*/)(?!/?$)", "^\\.(?!/?$)", "^\\./?$"],
              // Style imports.
              ["^.+\\.?(css)$"]
            ]
          }
        ]
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Finish line

And you're all set! The sorting should happen automatically when ESLint is run in the auto-fix mode.

Here's the code after sorted:

import React, { useState } from 'react';
import { Card, Header } from 'components';
import { Button } from 'ui-package';

import { generatePath } from '../../domain';

import { parseTableData } from './utils';
Enter fullscreen mode Exit fullscreen mode

Let's keep in touch! Any feedback is appreciated.
You can also find me on Twitter.

Top comments (11)

Collapse
 
hyphaene profile image
Maximilien Garenne

hey.
nice article !
Small typo => yarn install eslint-plugin-simple-import-sort

Cheers

Collapse
 
thejavascriptedtale profile image
Sahil Maniyar

Really helpful post thanks

Collapse
 
lovedeep5 profile image
lovedeep5

Thank you for sharing that, what if we want to do it without plugin?

Collapse
 
gaweki profile image
Andrel Karunia S

thank you. do you have configuration for SOLID principle?

Collapse
 
gregwoods profile image
Greg Woods

Love it, thanks.
I was kind of expecting a newline after the "react" group though. Any idea why it hasn't put one in?

Collapse
 
herberthk profile image
herberthk

Thanks nice article

Collapse
 
isidromar95 profile image
Isidro Martínez

Nice, Can i add comments before each group? e.g:
//Vue

//Core

//Helpers

Collapse
 
koylyakandriy profile image
Andriy Koylyak

Can u help me group my imports ?
stackoverflow.com/questions/742432...

Collapse
 
weltkind6 profile image
Ilya

Thanks! It's really works for me!

Collapse
 
afcreative profile image
Adam Farhansyah

helpful!

Collapse
 
thekoficoud profile image
the-koficoud

Excellent! thank you very much. Is a good tool for my OCD.