Root Directory Import in NextJS
In this lesson, we will continue studying imports in NextJS. But now we will explore a feature that is present in NextJS but absent in NodeJS.
The thing is, in NodeJS when importing we can use either relative paths (without a leading slash), or absolute paths from the operating system root (which creates problems when moving the project to another computer).
In real life, however, we need one more type of import - from the project root. This import is not built into NodeJS, but it is available in NextJS.
This import is enabled when installing NextJS. Remember, there was a question Would you like to customize the default import alias? If you answer Yes, then we get the ability to set imports from the project root.
Let's see how this is done. For example, let's say we have the following file structure:
- /src/
- data.js
- /app/
- test/
- page.jsx
- test/
As you can see, the file data.js is located
far from the file page.jsx.
Let's import our data file
into the page file. Let's use a
relative path for this:
import data from '../../data.js';
export default function Test() {
return <h1>Test</h1>;
}
As you can see, importing via a relative path
is not very convenient, as we have to start
the path with ../. Furthermore, if we move
our component to another location, the path
to the data file will break.
It would be more convenient to specify the path to the file
with data from the project root (the src folder is considered the root).
To do this, you need to write the
symbol @ at the beginning of the path.
Let's do this:
import data from '@/data.js';
export default function Test() {
return <h1>Test</h1>;
}
I emphasize again that such import is possible exactly in NextJS and only if during installation you answered the necessary question correctly. Simply put, this will not work in NodeJS or in pure JavaScript.
Given the following file structure:
- /src/
- /app/
- data.js
- /test/
- page.jsx
- /app/
Import the data file
into the Test component.
When importing, specify the path
from the project root.
Change your file structure to the following:
- /src/
- /app/
- data.js
- /test/
- /sub/
- page.jsx
- /sub/
- /app/
Make sure that the import from the project root still works without any problems.