Configure import order in a Next.js project

To configure import order in a Next.js project, you can use ESLint with the “sort-imports” or “import/order” rules from the “eslint-plugin-import” plugin. Here’s how you can set it up:

Install ESLint and the necessary plugins if you haven’t already

npm install --save-dev eslint eslint-plugin-import

Then, create a .eslintrc.json file in your project root if it doesn’t exist already. If it does, you can just add the rules to it. In your .eslintrc.json file, you can add the “import/order” rule like so:

{
  "plugins": ["import"],
  "rules": {
    "import/order": [
      "error",
      {
        "groups": ["builtin", "external", "internal"],
        "pathGroups": [
          {
            "pattern": "react",
            "group": "external",
            "position": "before"
          }
        ],
        "pathGroupsExcludedImportTypes": ["react"],
        "newlines-between": "always",
        "alphabetize": {
          "order": "asc",
          "caseInsensitive": true
        }
      }
    ]
  }
}

This will enforce a specific order to your imports:

  • Built-in modules (like fs and path)
  • External modules (like react and axios)
  • Internal modules (your own project’s modules)


The “newlines-between”: “always” option will enforce having blank lines between each group.

The “alphabetize” option will sort the imports alphabetically within each group.

The “pathGroups” option allows you to customize the position of certain modules within their group. In this case, it’s making sure react always comes before other external modules.

Then, run ESLint to check your project:

npx eslint --fix

This will automatically fix any issues with import order in your project according to the rules you’ve set.