loading...
Cover image for Sorting your imports correctly in React

Sorting your imports correctly in React

otamnitram profile image Martín Mato ・2 min read

While I am preparing my next article, I wanted to share with you this short post with an excellent configuration for your React or React Native apps.

Sorting your imports in a JS file has a lot of benefits. First at all makes it easier to see what you imported from specific packages, also if you group them, you can easily distinguish which imports are from third party packages or local imports.

It is annoying doing all the sorting manually, also, if you are someone who makes abusive use of the VS Code sort-imports like me, then when sharing your code, it is incompatible with the config of other developers. Here is where ESLint can help us.

ESLint to the rescue!.

As we know, ESLint is the most popular linter for javascript. I don't remember not using it in any of my react projects because it is handy to define a set of styling rules to make the code clear and consistent.

ESLint comes with an in-built import sorting rules that even they have beneficial properties, it doesn't fit what I need. So, I use eslint-plugin-import.

eslint-plugin-import is a plugin that extends the ESLint import rules. It doesn't have properties only to organize and to sort; also, it helps to prevent having issues like misspelling file path or packages names, among other things.

My settings

So, you can install the eslint-plugin-import library in your dev dependencies, add in the plugin array in your ESLint config file and start to use it.

One of the things I want to ensure in my react code is that the first import is the React package, just to follow the standard convention. Then, I want to group them separately, first all the third-party packages, and then all the local files.

So my rule is the next one:

"import/order": [
      "error",
      {
        "groups": ["builtin", "external", "internal"],
        "pathGroups": [
          {
            "pattern": "react",
            "group": "external",
            "position": "before"
          }
        ],
        "pathGroupsExcludedImportTypes": ["react"],
        "newlines-between": "always",
        "alphabetize": {
          "order": "asc",
          "caseInsensitive": true
        }
      }
    ],
  • The groups sets the order intended for every group.
  • pathGroups can group by path set by a pattern. In this case, I want to look for react import to be before any other import.
  • pathGroupsExcludedImportTypes defines import types. "React" will be handled as other type so it can be separated for the other external packages.
  • newlines-between separates each group with a new line in between.
  • alphabetize sort the order in which group will be sorted. I choose in ascending way and case sensitive.

Once you run ESLint your import statements in the code should look like this:

import React from 'react';

import { PropTypes } from 'prop-types';
import styled from 'styled-components/native';

import ErrorImg from '../../assets/images/error.png';
import colors from '../../styles/colors';

Conclusion

I hope this post can be helpful to someone.
Please feel free to make any suggestions or questions in the comment section.

Thanks for reading.

Discussion

pic
Editor guide
Collapse
gustaffweldon profile image
Good stuff and well done!

import/order works great until it hits code like:

import { b, c, a } from 'sth';

It will simply ignore { b, c, a } sorting. I have tried coupling it with sort-import but they are conflicting.

So, in the end, I will probably resort to simple-import-sort which does both, grouping and sorting in groups as well as import members.

Collapse
aamirafridi profile image
Aamir Afridi

Thanks for pointing to eslint-plugin-simple-import-sort simple to configure and worked great for me.

Collapse
masbossun profile image
Ryan Setiagi

Thanks for the config, I figured it out how to group react and react-native import first with this pattern

"pathGroups": [
          {
            "pattern": "react+(|-native)",
            "group": "external",
            "position": "before"
          }
        ],
Enter fullscreen mode Exit fullscreen mode
Collapse
aamnahakram profile image
Aamnah Akram

Thanks for this. My config is pretty much the same as yours except for groups

"groups": [ "builtin", "external", "internal", ["parent", "sibling"] ],

This gives me one more group of import statements for all files that are imports from ../ and ./ files

Collapse
otamnitram profile image
Martín Mato Author

Yes, that's great. Thanks!

Collapse
bytebodger profile image
Adam Nathaniel Davis

I really like the ESLint approach. FWIW, I recently wrote an article extolling the benefits of sorting your code in many other areas of the application as well:

dev.to/bytebodger/sorting-code-alp...

Collapse
oliverandrich profile image
Oliver Andrich

I prefer to use eslint-plugin-simple-import-sort for the same purpose. It lets me fiddle around with rules a bit more. At least I think I can't configure my rules with "import/order". But I need to give it a try again after your post. Thx.

Collapse
aashutoshrathi profile image
Aashutosh Rathi

You simply saved my day!

Collapse
abdelrahmanahmed profile image
Wahdan

And i thought i am alone by doing this, thanks for your contribution 🙌

Collapse
hoangleitvn profile image
Hoang Le

This is awesome.

How about if we use for Angular? Btw have you been able to use any ext that can auto reorder imports based on the eslint rule?

Collapse
otamnitram profile image
Martín Mato Author

To use for Angular, I think you should use a tool like typescript-eslint for ESLint support Typescript and then use the plugin as I mentioned in the article. In theory, this should work, but I didn't try myself.

Regarding extensions to help you auto-reorder, you have the ESLint extension. With the help of setting editor.formatOnPaste": true and editor.formatOnSave": true on the VS Code settings you should be able to sort automatically on save and paste using the ESLint rule.

Collapse
dance2die profile image
Sung M. Kim

Sweet~ I didn't know that you could enforce import rules with ESLint!

Thanks for sharing, Martín

Collapse
duasfh profile image
Pavel Shamparov

Does anyone experiences wrong regex behaviour with groupPath pattern?

Collapse
otamnitram profile image
Martín Mato Author

Can you specify your problem?

Collapse
itscosmas profile image
Cosmas Gikunju

I have been doing this manually😅. I feel stupid but now I'm not

Collapse
otamnitram profile image
Martín Mato Author

Glad it was helpful!.