DEV Community

anjalyyy1
anjalyyy1

Posted on

2 1

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.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Image of Stellar post

🚀 Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

AWS Industries LIVE!

AWS Industries LIVE! features AWS Partners discussing various topics related to their industry, their solutions, and how they can help customers.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️