Presentation ๐
When you go to GitHub and see other developers' code, most of them import their components like this๐
import Button from "../../../components/Buttons/Button"
This is called relative import. The relative import will start with either ./
,/
Or ../
.
I'm not saying this is not the right method and although there is no problem if you import this way, but if you have a very large and complex project the relative imports will look very complicated, like that.
import Button from "../../../../../../components/Buttons/Button"
However, there is a much better and cleaner way to import these components. This method is called absolute import. An absolute import will look like this ๐
import Button from "components/Buttons/Button"
Adding absolute imports to React Apps (CRA) ๐ก
Open your project in any code editor and create a new file in the root directory of your project named jsconfig.json
. Once you have created the file, paste the JSON below inside.
{
"compilerOptions": {
"baseUrl": "src"
}
}
This will instruct Webpack to use the src
directory as the base directory.
Conclusion โ
I hope you found this short article helpful. If you need any help, let me know in the comments section.
Let's connect on Twitter And LinkedIn
๐ Thanks for reading, see you next time