Photo by Lili Popper on Unsplash
Using absolute paths and breaking out of directory hell in React imports.
../../../../../../
If you were in a war and you needed to fortify your defenses, the above would have made some sense.
But, not while trying to import a different type of module in React and doing this
../../../todos
What happens if you try to restructure the todos file and try to bring it up by one level in your folder structure ??
This will be a huge pain of migrating through every file that has a relative import and changing it to suit your updates in which case you will certainly go:
¯\_(ツ)_/¯
Wait, relative ...what ??
There are generally 2 ways of importing files - using relative paths or absolute paths.
A relative path is basically the path relative to a particular file in which you are including that path.
Ex: Importing "actions/todos" in "/components/todos/list", you might write in your list.js
:
import todos from "../../../actions/todos";
An absolute path is where the path is taken with respect to a fixed origin.
In the above example, assuming components
and actions
to be in a top-level src
folder.
The absolute import can be written as:
import todos from "actions/todos";
If you now try restructuring this file to any level inside the src folder, the absolute import never breaks and keeps your imports intact and working.
Now, on restructuring you will certainly go:
╭(◔ ◡ ◔)/
As it turns out it is pretty easy to set up absolute imports in React setup with Create-React-App.
Add an env file with this line
NODE_ENV = "src/"
and you are good to go. This identifies your src
folder to be the topmost level from which paths should be considered.
So, when you write import todos from "actions/todos"
it will look for todos file in src/actions/todos
.
PS: This is not the only way to use absolute imports and I will encourage you to find out a couple of more alternate ways. Happy Learning!