ESLint sort imports by package name

Viewed 2047

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
            }
        ],
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"],
      },
    ],
Related