DEV Community

Cover image for Using absolute imports in React app
Dominik Ilnicki
Dominik Ilnicki

Posted on

Using absolute imports in React app

Some time ago, I found out how to use absolute imports in React. I regret that I found it so late because it's extremely handy when it comes to bigger projects with nested files structure.

Using absolute imports means instead of importing React component like this: import Button from '../../../Button/Button' you can do it like this: import Button from 'components/Button/Button'.

Here is a quick tutorial of how to get it going with Create React App 3.

  • Create a jsconfig.json file in your project's root directory.
  • Paste that JSON config
{
  "compilerOptions": {
    "baseUrl": "src"
  }
}
Enter fullscreen mode Exit fullscreen mode

The above snippet will instruct Webpack to use the src directory as a base one.

  • Done. From now you can use absolute imports inside your whole project

Top comments (9)

Collapse
 
ramblingenzyme profile image
Satvik Sharma

We've gone round the loop on this at my work, and it's obnoxious to have to teach every tool you use about using absolute imports, Webpack, Jest, Babel, Typescript, Eslint, TSLint and so on.

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

Totally agree with this. I really despise the look of those ../../../../ imports. But getting rid of them can be equally problematic, depending upon your toolset.

Collapse
 
sirseanofloxley profile image
Sean Allin Newell

Preach

Collapse
 
thuanpv1 profile image
thuanpv1

my project was created by the command npx create-react-app last year. I have just tried to apply your solution of importing other components. However, i still get the message "Module not found: Can't resolve '...". it looks like the import by this way is correct because i can jump into the component by pressing ctrl + left mouse click into the path. so i don't know why compiler doesn't recognize the new import path. have you ever bump into this kind of issue ? and what is your solution to cover this case ?

Collapse
 
dominikilnicki profile image
Dominik Ilnicki

Hi, that solution works only with projects created using create-react-app in version 3 (released in April 2019). If your project was bootstrapped with v2 you can use old school way to achieve absolute imports. Create .env file with that line NODE_PATH=src/. That should work for you.

Collapse
 
bmitchinson profile image
Ben Mitchinson

..... this is so much better than ../../../

i'm offended I didn't know about this. Thank You!
I'm assuming it works in a tsconfig as well ?

Collapse
 
theonlybeardedbeast profile image
TheOnlyBeardedBeast

Yep

Collapse
 
mogaozq profile image
Mohammad Barbast

Awesome, Thanks

Collapse
 
ace4port profile image
Abdullah Waqar

Control + Click doesn't work on VS Code

Anyone got solutions for it?