How to quickly sort imports with Prettier
• 3 min read
Introduction
Having disorganized imports bothers me deeply when working on a project. I typically like to keep the entire codebase as organized as possible as it makes sifting through the files much easier. With the help of prettier and a plugin, we can easily sort imports!
As a side note if you’re using ESLint I have another article to sort imports using that.
Sort Imports: Setting everything up
First, let’s install the necessary dependencies. We’ll need just two: prettier and the plugin 📦.
Bash/Shellnpm install prettier @trivago/prettier-plugin-sort-imports --save-dev
Sort Imports: Configuring the Rules
Now we can go ahead and start configuring our rules. This plugin receives an array of strings. It uses these strings to decide the order of our imports!
So for example in my small sample project I have the following files:
So we’ll have to set up the rules to configure them. I typically like the following order:
- Package/third-party imports
- Project imports
- Relative imports
This will cover mostly everything! So let’s create a .prettierrc (a prettier configuration file) at the route of our project.
Inside that file add the following rule:
JSON{
"importOrder": ["^components/(.*)$", "^[./]"],
"importOrderSeparation": true,
"importOrderSortSpecifiers": true
}
Let’s break down these options. They’re parsed through regex (yes I know the devil’s tongue). But it’s roughly the same format for every import type.
First, any type of regex that isn’t included will be sent to the top. This is crucial. As the unincluded third-party dependencies will just go to the top as we want. Afterward, we follow up without aliased components folder, and then our relative imports. I also have two additional rules to add linebreaks between the import groups and to sort specifiers in an import declaration
In this GitHub repo, you can find a list of the other rules that are available.
Sort Imports: The Result
Now as soon as we save the file (if you happen to have format on saving in whichever IDE you’re using) or format the file you’ll see the following result:
Wow, that look’s much cleaner 👌🏼
Conclusion
Hopefully, with that, you have more organized imports in your projects!
If you liked this feel free to connect with me on LinkedIn or Twitter
Check out my free developer roadmap and weekly tech industry news in my newsletter.
If you see any typos or errors you can edit the article directly on GitHub
Hi, I'm Diego Ballesteros 👋.
Stay on top of the tech industry and grow as a developerwith a curated selection of articles and news alongside personal advice, observations, and insight. 🚀
No spam 🙅♂️. Unsubscribe whenever.
You may also like these articles:
- 2023-06-05T00:41:29.681Z
- 2022-10-25T11:29:26.663Z
- 2022-10-17T14:44:10.229Z
- 2022-10-10T14:02:10.349Z