1 min read

Absolute Imports for Next.js

Want to avoid really long import paths with your Next.js project? Setup a jsconfig.json. Here is how to tell babel to use imports from your root.
Absolute Imports for Next.js
Photo by Paul Teysen / Unsplash

One thing that gets annoying with any node or modern JavaScript development, is that as the project grows, so does the import paths. As I add more folders, and nest them, the ../../../ grows longer as I need to get to the base level of my repository to get a new component or library method.

This is especially true with Next.js and any other folder based routing system. When using Next.js, I don’t want to maintain a server or a webpack config. I did this early on when adopting Next.js 1.0, but have really disliked it. With Next.js 10 and other recent versions, I don’t see this need anymore for my purposes.

Luckily, we can reset the baseUrl with babel directly, so we don’t have to setup a custom webpack override, or anything else. Just create a jsconfig.json at the root to define the baseUrl. Then instead of having to go back to the root with ../you can just reference files as if you were already in the root.

jsconfig.json

{
  "compilerOptions": {
    "baseUrl": "."
  }
}

This works because we tell Babel how to reference our files, overriding the default behavior that uses relative paths. I don’t think this makes sense for all projects, but it certainly helps for larger projects.

The one drawback to this approach is that when you are reference files in the same folder, you have to go from the root every time. So instead of being able to ./ComponentA you have to use components/ComponentA. But I still find this cleaner in the end.