Absolute import for your React Typescript project

anjalyyy1

anjalyyy1

Posted on April 10, 2022

Absolute import for your React Typescript project

Working on any project, one of the most annoying and confusing things has to be adding relative imports. It always creates confusion and is difficult to change whenever you ship your component to any other folder/component. We are always worried if it would break anything!!!. Absolute imports to the rescue...

So instead of importing files like ../../../components/header, with absolute imports we can import file like components/header and now we don’t care about the relative positions of the file. We only care about the position of the file relative to the root of the project.

Benefits:

  • Clean and maintainable code
  • Copy pasting imports to other components is a lot more easier.
  • Easily locate files when absolute imports are used.

For React projects created using typescript, we have a tsconfig.json file, where we just want to add:

{
  "compilerOptions": {
    ...
    "baseUrl": "src"
  },
  "include": ["src"]
}
Enter fullscreen mode Exit fullscreen mode

Now restart your app to see the imports working for you. You can sometimes this error see the Cannot find module components/header, to resolve that you just have to restart VS Code, and that should do the work.

If the issue still persists, you can Open the settings(Ctrl + ,) > search for Import module specifier, under Typescript settings, change setting to auto or non-relative, VS Code will decide how the import has to be done based on your tsconfig.json file. You may need to restart the IDE again for this to take effect.

Let me know in the comments if this worked for you.

Thanks.

💖 💪 🙅 🚩
anjalyyy1
anjalyyy1

Posted on April 10, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related