Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ESLint sort imports by package name

I'm trying to sort my imports by package name but it seems like it's not supported based on what is available from the docs.

Is there a way for this to work?

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

The code above fails because it wants BrowserModule to be on the first line. But I want this to be considered correct since I want to order by package name.

Here's my ESLint config.

"sort-imports": [
            "error",
            {
                "ignoreCase": true,
                "ignoreDeclarationSort": false,
                "ignoreMemberSort": false,
                "memberSyntaxSortOrder": [
                        "none",
                        "all",
                        "multiple",
                        "single"
                ],
                "allowSeparatedGroups": true
            }
        ],
like image 315
raberana Avatar asked Dec 18 '25 12:12

raberana


2 Answers

I am using eslint-plugin-import and it supports such functionality. Posting my config for reference. It would enforce that React imports are always first, then imports that are starting with @my_org and then the rest is configured based on groups' order

"import/order": [
      "error",
      {
        "alphabetize": {
          caseInsensitive: true,
          order: "asc",
        },
        "groups": ["external", "builtin", "parent", ["sibling", "index"]],
        "newlines-between": "never",
        "pathGroups": [
          {
            group: "external",
            pattern: "react",
            position: "before",
          },
          {
            group: "external",
            pattern: "@my_org/**",
            position: "after",
          },
        ],
        "pathGroupsExcludedImportTypes": ["builtin"],
      },
    ],
like image 56
Daniel Stoyanoff Avatar answered Dec 20 '25 03:12

Daniel Stoyanoff


The base ESLint rule just doesn't support it - it sorts by name.

You can use a different sorting rule like the one here.

https://www.npmjs.com/package/eslint-plugin-simple-import-sort

like image 38
Brad Zacher Avatar answered Dec 20 '25 02:12

Brad Zacher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!