How to Use ESLint for TypeScript Import Ordering

Migel Hewage Nimesha Feb 02, 2024
How to Use ESLint for TypeScript Import Ordering

This article will discuss how to use ESLint to style or order your imports section easily. The sort-imports and import/order rules in ESLint will be discussed.

Use ESLint for TypeScript Import Ordering

A clean code is always better; it motivates future contributions and maintenance. Hence, maintaining consistent code conventions and formatting styles are important aspects.

Static code analysis is also beneficial for interpreted languages like JavaScript or TypeScript. It will help you identify errors in advance.

Linters help identify these types of stylistic and programmatic issues.

The ESLint is one of the widely used linter. It has been used to identify TypeScript code styling issues and fix them.

In larger projects, one of the main styling problems is to manage imports. Developers come and contribute to the codebase frequently.

They add new import statements, and the section grows. ESLint can be used to organize the imports section more cleanly.

ESLint sort-imports Rule for TypeScript Import Ordering

The ESLint configuration file can be used to add custom rules. Usually, it is called the eslintrc file, consisting of JSON formatted rules, as shown in the following.

TypeScript ESLint Configuration File

Getting several imports makes the developer’s life easy if those have been alphabetically sorted. It will also make it easy to find specific members inside the import section.

The sort-imports ESLint rule with some custom configurations will fulfill this.

Let’s assume that we got the import statements, as shown in the following.

import 'module-1.js';
import * as employee from 'employee.js';
import * as company from 'company.js';
import {supervisor, agent} from 'company-context.js';
import {job, designation } from 'company-context-2.js';
import {bearer} from 'bearer.js';
import agent from 'agent.js';

import divide from 'utildivide.js';
import subscription from 'utilsub.js';
import add from 'utiladd.js';

Next, we can add the sort-imports rule into the ESLint configuration file, as shown in the following.

"rules": {
        "sort-imports": ["error", {
            "ignoreCase": true,
            "ignoreDeclarationSort": false,
            "ignoreMemberSort": false,
            "memberSyntaxSortOrder": ["none", "all", "multiple", "single"],
            "allowSeparatedGroups": false
        }]
    },

The sort-imports rule can raise both the error and warning types. Apart from that, it has other optional parameters that can be configured according to your need.

The ignoreCase parameter can be set to true if you want ESLint to ignore the case and order of imports. You can run the below command to ESLint to check for the imports.

npm run lint

This would raise errors in the above example script because it has not been ordered properly. If you pass the --fix flag with the above command, ESLint will fix the issues in your imports.

npm run lint --fix

Hence, the correct version of the above imports would look like the following.

import 'module-1.js';
import * as company from 'company.js';
import * as employee from 'employee.js';

import {agent, supervisor} from 'company-context.js';
import {designation, job} from 'company-context-2.js';
import agent from 'agent.js';
import {bearer} from 'bearer.js';

import add from 'utiladd.js';
import divide from 'utildivide.js';
import subscription from 'utilsub.js';

It sorts these imports according to the following order.

  1. User member syntax
  2. Alphabetical sorting by the first member or alias

ESLint import/order Rule for TypeScript Import Ordering

The import/order rule is more powerful than the sort-imports rule we discussed previously. This offers a variety of options to order our imports based on the module’s nature, such as built-in module, external module, parent module, etc.

Hence, this is more advanced than the alphabetical sort we saw in the sort-imports rule.

To plug this into our ESLint, we should install the eslint-plugin-import plugin. Let’s run the npm i command to install it for our project, as shown in the following.

npm i eslint-plugin-import --save-dev

The --save-dev will save this dependency to our project’s package.json file. Now, we can use the import/order rule in our ESLint configuration file, as shown in the following.

"rules": {
        "import/order": ["error",
            { "groups" :
            [
                "external",
                "builtin",
                "internal",
                "sibling",
                "parent",
                "index"
            ]
            }
        ]
    },

The groups section has been configured to order the imports first by external modules, then the built-in modules, and so on. Hence, the following is a valid import section.

// "external" modules
import _ from 'lodash';
import express from 'express';
// "builtin" modules
import fs from 'fs';
import path from 'path';
// "internal" modules
import employee from 'src/employee';
// "sibling" modules
import netsalary from './payrole';
import epf from './payrole/epf';
// modules from a "parent" directory
import admin from '../admin';
import role from '../../admin/role';
// 6. "index" file
import main from './';

The above import section is valid according to the ESLint configurations.

Therefore, ESLint can be used to style or order your imports section easily. It makes the developer’s life easy and acts as a guideline for all newcomers to your codebase.

Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

Related Article - TypeScript Import