Sorting imports on save in React projects with ESLint.

Kolby Sisk
Udacity Eng & Data
Published in
2 min readDec 3, 2021

--

Photo by Cesar Carlevarino Aragon on Unsplash

Figuring out how to automatically sort imports on save was much harder than I’d like to admit. Maybe it’s because I’m particularly picky about the order, or that I wanted it to integrate nicely with the tools I’m already using. Either way, I figured it out and here’s how I did it.

Solution Requirements

  1. Customizable ordering. I want React imports first
  2. Integrates with VS Code and runs on save
  3. Utilizes ESLint (I will assume you already have ESLint installed)
My ideal import sorting

How to do it

  1. Install the ESLint extension.
  2. npm i eslint-plugin-simple-import-sort -D
  3. Open VS Code settings and search for codeactionsonsave, then press Edit in settings.json.

3. Add the following config. This tells VS Code to run eslint --fix when you save a file.

"editor.codeActionsOnSave": {
"source.fixAll": true
}

4. Add the following config to your .eslintrc.json file.

{
"extends": [],
"plugins": ["simple-import-sort"],
"rules": {
"simple-import-sort/imports": "error",
"simple-import-sort/exports": "error"
},
"overrides": [
{
"files": ["**/*.js", "**/*.ts", "**/*.tsx"],
"rules": {
"simple-import-sort/imports": [
"error",
{
"groups": [
// `react` first, `next` second, then packages starting with a character
["^react$", "^next", "^[a-z]"],
// Packages starting with `@`
["^@"],
// Packages starting with `~`
["^~"],
// Imports starting with `../`
["^\\.\\.(?!/?$)", "^\\.\\./?$"],
// Imports starting with `./`
["^\\./(?=.*/)(?!/?$)", "^\\.(?!/?$)", "^\\./?$"],
// Style imports
["^.+\\.s?css$"],
// Side effect imports
["^\\u0000"]
]
}
]
}
}
]
}

5. Optionally, run npx eslint . —-fix to do an initial pass over your project.

That’s it!

You can customize the overrides to your liking. Check out eslint-plugin-simple-import-sort for more documentation.

--

--

Builder of software with a passion for learning. I specialize in web development and user experience design. www.kolbysisk.com