I recently started learning Next.js and used path aliases in a project, and guess what? It significantly improves the quality of my code. Are you curious as to how this is possible? Let me show you how it's done...
What is the problem? "Relative Path Hell"
Typing paths is time-consuming and error-prone and it can be complicated at times. Even with code completion capabilities like IntelliSense (which is supported by practically every IDE or text editor), as your codebase expands, this might become increasingly difficult.
Here's an example of a relative path that requires accessing many path levels when attempting to import.
How can we solve this?
Shortening our import paths, which can be accomplished via "Path Aliases," can make things a little easier.
How can we build up path aliases in a project that is structured like this?
- To make use of path alias, create a
"jsconfig.json"
file or ("tsconfig.json"
if using typescript) in the project root and configure it as shown below.
What next?
There's nothing further to set up; you can now use path aliases in your application while importing.
In conclusion, every update to the "json" file necessitates a server restart.
Top comments (7)
Well this would not work and components will not be resolved.
Components are in your
src
folder. But the compilation is done in the root folder. You need to change it.Or by changing the baseUrl
I think his solution will work for him since his
component
folder is directly under theroot
folder.His approach worked fine for me. Your second approach of changing the baseUrl also worked fine. But your first approach didn't work.
Just to add some contrast to this because devops.
Webpack also supports aliases which work across file types.
Enlightening boss. Good Job
I'm proud of you.
anyone else having issues with alias' not working with Storybook?
Absolute path for jsx imports work fine, converting imports to alias' causes "Couldn't find story matching" 😪
Oh yeah! Storybook doesn't recognize alias imports. I have been having that issue working with Storybook and Next.js "@" imports.