How to Sort Import Declarations With Prettier

When you are coding in your favorite editor with an auto import feature, your import declarations will have no particular order and you might cringe a bit if you were like me. In this post, I will teach you how to use prettier to sort those import declarations for you.

Sort Import Declarations With Prettier

First, install Prettier and a plugin to sort import from Trivago as a development dependencies in your project.

            npm install --save-dev prettier @trivago/prettier-plugin-sort-imports
        

And then create a .prettierrc.json on your project's root folder:

Note: if you already have a prettier config, simply add these 3 keys to your existing config.

And it's ready! Try running npx prettier --write . on your project and you'll see that all of your import declarations are neatly organized.

You can also configure additional rules using regular expressions and move third-party imports at desired place if you want:

"importOrder": ["^@/(.*)$", "<THIRD_PARTY_MODULES>", "^[./]"]

Thanks for reading, I hope you learn something. 😉


Written by Dimitri Wahyudiputra

an Educator/Software Engineer that loves solving problems with code.

« posts index