Crossing reviews becomes a very common activity today in engineering behavior. To help us review changes for pull/merge requests easier, sorting imports can help us a much. The codebase becomes more professional and more consistent, reviewers will be happier, and the review process will be faster, focusing on the implementation changes ONLY.
Have you ever thought about how to sort imports in TypeScript projects automatically?
Let me show you how to archive sorting imports automatically in TypeScript projects with ESLint!
Photo by Tim van der Kuip on Unsplash
- Have TypeScript projects
- Have some basic knowledge about ESLint - a JavaScript linting tool
- Have time to go through all steps in this article π
- Install
devDependenciespackages related toeslintin TypeScript project
yarn add -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin prettier eslint-config-prettier eslint-plugin-prettier- Create
eslintthe base configuration for TypeScript project
.eslintrc.js file
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
},
env: {
node: true,
},
plugins: ['@typescript-eslint', 'prettier'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
]
};- Configure ESLint base
sort-importsrules
With this native ESLint rule sort-imports, I use it to sort member imports in the import statements. You can notice that it supports more features for sorting imports. But I will use another plugin for advanced import sorting
Outcome:
import { c, b, a } from 'package-to-import'
=> import { a, b, c } from 'package-to-import'
- Update
.eslintrc.jsfile by addingrules
.eslintrc.js file
module.exports = {
// Extends the previous ESLint configuration by adding rules
// <--! Previous configuration comes here !-->
rules: {
'sort-imports': [
'error',
{
ignoreCase: false,
ignoreDeclarationSort: true, // don"t want to sort import lines, use eslint-plugin-import instead
ignoreMemberSort: false,
memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'],
allowSeparatedGroups: true,
},
]
}
};- Configure
importrule witheslint-plugin-importpackage
-
Install
eslint-plugin-importpackage to use plugin import in ESLintyarn add -D eslint-plugin-import
-
Configure
importrulesIn this step, we configure the order of our imports. There are two important pieces of information. There are
groupswhich indicates how we get import statements sorted, andalphabetizewhich indicates how we sort import lines by alphabetNow, let's update the current ESLint configuration by adding new
importrules.eslintrc.js file
module.exports = { // <--! Previous configuration comes here !--> plugins: ['@typescript-eslint', 'prettier', 'import'], // Add "import" plugin extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended', // Extends two more configuration from "import" plugin 'plugin:import/recommended', 'plugin:import/typescript', ], rules: { // <--! Previous rules come here !--> // turn on errors for missing imports 'import/no-unresolved': 'error', // 'import/no-named-as-default-member': 'off', 'import/order': [ 'error', { groups: [ 'builtin', // Built-in imports (come from NodeJS native) go first 'external', // <- External imports 'internal', // <- Absolute imports ['sibling', 'parent'], // <- Relative imports, the sibling and parent types they can be mingled together 'index', // <- index imports 'unknown', // <- unknown ], 'newlines-between': 'always', alphabetize: { /* sort in ascending order. Options: ["ignore", "asc", "desc"] */ order: 'asc', /* ignore case. Options: [true, false] */ caseInsensitive: true, }, }, ], } };
- Configure
import resolverwitheslint-import-resolver-typescriptpackage
Why do we need this package? It helps us resolve package, imports, module under the TypeScript project. Some of us may use compilerOptions.baseUrl or compilerOptions.paths in the tsconfig.json configuration file.
-
Install
eslint-import-resolver-typescriptpackageyarn add -D eslint-import-resolver-typescript
-
Configure
eslint-import-resolver-typescriptpackageExtends the current ESLint configuration by adding new section called
settings.eslintrc.js file
module.exports = { // Extends the previous ESLint configuration by adding `settings` // <--! Previous configuration comes here !--> settings: { 'import/resolver': { typescript: { project: './tsconfig.json', }, }, }, };
To help us trigger ESLint auto fix feature, to resolve a lot of fixable ESLint issues come from your current working file.
Create new VSCode settings.json file under ./vscode/settings.json
{
"editor.formatOnSave": false,
"eslint.validate": [
"typescript"
],
"editor.codeActionsOnSave": {
"source.fixAll": true
}
}BONUS section:
In case, you do not work on Visual Studio Code IDE, You can add new script command to run sort imports manually
package.json file
{
// <--! Current content of the package.json file goes there !-->
"scripts": {
"lint": "eslint --ext .ts ./src",
"lint:fix": "npm run lint -- --fix"
}
}Now you just run ONLY one single command yarn lint:fix to fix all coding style issues catch by ESLint. Easy work, right? π
To sum up, all of the steps we need to get our TypeScript project imports sorted automatically, there are 3 steps:
- Configure ESLint base for our TypeScript project
- Configure ESLint to sort imports
- Configure VSCode to sort imports automatically
And that is all from me for this time, thank you for reading my sharing article. Hope you can find it helpful!
Any concerns, or questions, do not hesitate to put it in the response section below. See you next time!
- ESLint
sort-imports - ESLint
importplugin - ESLint
importTypeScript resolver plugin - My sample TypeScript project
This article is also published on How to sort imports like a pro in TypeScript | by Fast Nguyen | Weekly Webtips | May, 2022 | Medium


Thank you a lot. No more "import order" comments in my PR review π