Don’t you hate when you need to import a module, but you need to import 2 directories up? Or was it 3?!
I think everyone’s felt the pain if he has written any React code. :)
What is a relative import?
Here is a sample code which imports a Redux action creator:
import { removeUser } from "../../../actions/removeUser";
This hurts the most when you move a component or create a new one which needs to import something which is waaay up in the project’s structure…
What is an absolute import?
Now that we’ve seen what’s a relative import, we can show what’s an absolute import.
Here it is:
import { removeUser } from "actions/removeUser";
Way better, huh?
I don’t know about you, but I really don’t want to specify all the ../../..
paths. Also, it’s ugly!
Okay, but how?
Well, it documented in the create-react-app docs, which are pretty good actually!
You need to create a jsconfig.json
file at the root of your project, NOT the src
directory, with the following content:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"],
"exclude": ["node_modules"]
}
I’ve added the exclusion of node_modules
. Not sure why was this needed, but I experienced some issues when it was not present. Maybe I’ll write a follow-up post later on that topic some day.
Is that all?
Well, this works great if everything you need to import is located under src/
directory, but what if I have a tests
directory with all the test helper functions you need, which is at the same level with the src
directory? Well, you’re out of luck… :(
Or at least you were! Now (some 9-10 months ago…) the following pull request was merged! The most notable thing added is the support to override moduleNameMapper
for jest
!
What this means is we can map our tests
modules the way we want! Here is what I do in my package.json
:
"jest": {
"moduleNameMapper": {
"tests/(.*)": "<rootDir>/tests/$1"
}
}
Now if we import tests/constants
in our tests we’re going to get the proper modules resolved, no need to specify a relative path anymore!
But VS Code can’t navigate to my JSX components?!
Well… yeah. There is an issue, you just need to add the following line under compilerOptions
:
"jsx": "react"
NOTE: This was taken from the following response.
Final result
Here is the final result, ready for copy/paste, in all its glory:
{
"compilerOptions": {
"baseUrl": "src",
"jsx": "react"
},
"include": ["src"],
"exclude": ["node_modules"]
}
Conclusion
That’s it! I find this very useful and I am pretty sure it boosts my productivity.
Writing the absolute imports may give you an insight if you’ve structured your project badly as well!
Until next time! ;)