evolved.io logotype

#TypeScript #Prettier #Imports #CodeStyle

Effortless Sorting of Imports with Prettier

Add consistency to your TypeScript projects by sorting imports using Prettier and a helpful plugin.

Avatar
Dennis GaidelJanuary 15, 2024

Prettier is a well known and widely adopted code formatter. Due to its opinionated nature, it does not provide many configuration options.

One aspect that is not covered is the order of the imports: Fortunately there is a plugin, prettier-plugin-sort-imports, that adds this missing functionality.

Goal

My preferred import order is to

  • Import Sentry for error reporting first
  • Put React imports next
  • Followed by other third party library imports
    • First the ones that are not prepended by an @ sign
    • Then the ones with an @ sign prefix
  • And in the end the project's relative imports ordered by proximity
    • ./ should come before ../, which comes before ../../ and so on

In the end it looks something like this:

import * as Sentry from '@sentry/nextjs'

import { useState } from 'react'

import Image from 'next/image'
import Router from 'next/router'

import { Popover } from '@headlessui/react'

import { Article } from './article'

import { GoogleAnalytics } from '../components/google-analytics'
import { PrivacyContext, PrivacyManager } from '../components/privacy-manager'

What's also great about this plugin is, that it does not only sort the module specifiers, but the named imports inside the curly braces as well.

And it can also group the imports putting a blank line between each of them, so you can easily navgiate them.

Configuration

This is how my .prettierrc.json looks like to achieve this order:

{
    "importOrder": [
        "^@sentry/nextjs$",
        "^react$",
        "^[^@./]",
        "^@[^/]*$",
        "^@",
        "^\\.\\/",
        "^(\\.\\.\\/){1}[^\\.]",
        "^(\\.\\.\\/){2}[^\\.]",
        "^(\\.\\.\\/){3}[^\\.]",
        "^(\\.\\.\\/){4}[^\\.]",
        "^(\\.\\.\\/){5}[^\\.]",
        "^(\\.\\.\\/){6}[^\\.]",
        "^(\\.\\.\\/){7}[^\\.]",
        "^(\\.\\.\\/){8}[^\\.]"
    ],
    "importOrderGroupNamespaceSpecifiers": true,
    "importOrderSeparation": true,
    "importOrderSortSpecifiers": true,
    "plugins": ["@trivago/prettier-plugin-sort-imports"]
}

The ordering of the local imports by proximity to the current folder is achieved by separate rules, that are almost identical.

(\\.\\.\\/){2} defines how many levels above (../) the current folder the file can be found. And [^\\.] ensures, that the pattern is not followed by another ../ in order to avoid overlaps.

Conclusion

I'm all about consistency and automating wherever possible, so finding the prettier-plugin-sort-imports was a great win for me. It's flexible enough to adjust to my preferences, which has been a huge help. If you're aiming for similar consistency in your import patterns, this plugin’s setup might just do the trick for you.