The benefit of Import Ordering in Node.js

I saw a post from a backend enthusiast on my LinkedIn timeline today. He elaborated on minor improvements that bring massive benefits in terms of quality. This fits perfectly with my current focus: quality in Node.js projects. Therefore, today I'll show you a slight adjustment in the Node.js context with a significant impact: import sorting.

2 minutes

Why I Sort Imports in TypeScript Files

Since I started developing software, I have read more code than I write. There are two distinct times when I read code: first, when I'm tasked with adding new features or fixing bugs, and second, when I take responsibility for changes made by other team members through a code review because I believe they're good.

To ensure a review's change log includes only functionality changes and not code formatting, teams agree on code formatting rules. This is precisely where my argument for sorting imports comes in:

  • Readability: I can see at a glance what was imported and its source.
  • Maintainability: What's easier to read is easier to maintain.

Therefore, my recommendation is clear: sort the imports. Ideally, do it automatically. This improves both readability and maintainability. Additionally, it reduces the number of merge conflicts and eliminates team debates about preferences. So let's take a look at how to set this up.

How I implement this in Node.js

ESLint, in conjunction with Prettier, handles the automation. The magic behind this functionality is in the NPM package @trivago/prettier-plugin-sort-imports. In addition to basic sorting, the plugin also lets you configure settings if your team has preferences. I define my projects as follows:

module.exports = {
  // ...
  plugins: ['@trivago/prettier-plugin-sort-imports'],
  importOrder: ['^@konzentrik/(.*)$', '^@/(.*)$', '^src/(.*)$', '^[./]'],
  importOrderSeparation: true,
  importOrderSortSpecifiers: true,
  importOrderParserPlugins: ['typescript', 'decorators-legacy'],
}

This is what my .prettier.cjs looks like.

Do you sort things, and if so, how? Or do you have a completely different opinion?

Let's talk
call to action background image

Subscribe to my newsletter

Receive once a month news from the areas of software development and communication peppered with book and link recommendations.