DEV Community

Cover image for How to auto sort imports in frontend, example with typescript & nextjs
Muhammad Ali (Nerdjfpb)
Muhammad Ali (Nerdjfpb)

Posted on • Originally published at blog.nerdjfpb.com

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

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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.

If you are using vscode just add this in your setting JSON file then it’ll apply prettier every time you save

  "editor.formatOnSave": true,
Enter fullscreen mode Exit fullscreen mode

Source Code

You can find it here – https://github.com/nerdjfpb/auto-sort-import-example

Questions?

Drop a dm on – twitter

Want to be part of an amazing programming community and participate in free programming events?

Join our Discord server

Want to hire me for your next project?

Connect me with linkedin

Top comments (0)