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
devDependencies
packages related toeslint
in TypeScript project
yarn add -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin prettier eslint-config-prettier eslint-plugin-prettier
- Create
eslint
the 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-imports
rules
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.js
file 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
import
rule witheslint-plugin-import
package
-
Install
eslint-plugin-import
package to use plugin import in ESLintyarn add -D eslint-plugin-import
-
Configure
import
rulesIn this step, we configure the order of our imports. There are two important pieces of information. There are
groups
which indicates how we get import statements sorted, andalphabetize
which indicates how we sort import lines by alphabetNow, let's update the current ESLint configuration by adding new
import
rules.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 resolver
witheslint-import-resolver-typescript
package
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-typescript
packageyarn add -D eslint-import-resolver-typescript
-
Configure
eslint-import-resolver-typescript
packageExtends 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
import
plugin - ESLint
import
TypeScript 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 😄