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"
}
}
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)
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.
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.Preach
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 ?
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 lineNODE_PATH=src/
. That should work for you...... 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 ?
Yep
Awesome, Thanks
Control + Click doesn't work on VS Code
Anyone got solutions for it?