How to auto sort imports in frontend, example with typescript & nextjs

Muhammad Ali
2 min readJun 12, 2023

As a frontend developer, I import a lot of things on my every file and they look scary after a while! So I was looking for a way to solve this and I found a quick and easy solution which can use on any project I work on.

There are multiple ways to do the sorting and I always look for the easy and I always do that.

So here is an example of how I’m doing it in my nextjs project. After creating a new nextjs project. I install 2 packages –

npm i -D prettier @trivago/prettier-plugin-sort-imports

Now I add a .prettierrc for my project and it contains

{
"singleQuote": true,
"importOrder": [
"<THIRD_PARTY_MODULES>",
"^@internal/(.*)$",
"^[./].*(?<!\\.(c|le|sc)ss)$",
"^[.]/[-a-zA-Z0-9_]+[.](module)[.](css|scss|less)$"
],
"importOrderSeparation": true,
"importOrderSortSpecifiers": true,
"printWidth": 120
}

I went with my configuration you can go with one you like more. Find out more by clicking here

I generally use vscode and I configured always use prettier for sorting (Also installed a prettier extension). This helps me to apply the prettier on each save.

--

--

Muhammad Ali
Muhammad Ali

Written by Muhammad Ali

An otaku who loves computer. Love to write and help others through my work. Have a look on my Instagram https://www.instagram.com/nerd_jfpb/

No responses yet