Skip to main content
whitep4nth3r logo

11 Jul 2021

1 min read

How to avoid using relative path imports in Next.js

Say goodbye to ../../../../really/long/and/silly/paths/to/components in your Next.js application and define absolute imports with a jsconfig.json file.

Does this look familiar? 🤯

import MyComponent from "../../../../../components/MyComponent";
import ADifferentFile from "../../../some/other/dir/ADifferentFile";

Relative import paths to files in any application can be tricky to manage. Often we rely on the intelligence of our IDEs to tell us how many dot-dot-slashes to type when we're importing files that are nested many directories deep. If you're working with Next.js — there's a better way!

Define your base directories — or module aliases — in a jsconfig.json file at the root of your Next.js project.

Here's the jsconfig.json file I use for the code that powers whitep4nth3r.com.

{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@components/*": ["components/*"],
"@contentful/*": ["contentful/*"],
"@layouts/*": ["layouts/*"],
"@styles/*": ["styles/*"],
"@utils/*": ["utils/*"]
}
}
}

Using module aliases, import paths at the top of files are self-documenting and easier to write, meaning you can focus on writing code rather than traversing spaghetti directories. It's beautiful.

import PageMeta from "@components/PageMeta";
import RecentPostList from "@components/RecentPostList";
import SocialCards from "@components/SocialCards";

import ContentfulBlogPost from "@contentful/BlogPost";

import MainLayout from "@layouts/main";

import Styles from "@styles/BaseStyles.module.css";

import { Config } from "@utils/Config";

Read more about absolute imports and module path aliases on the Next.js documentation.


Salma with her hands gesticulating wildly, smiling, against a grey background.

Salma Alam-Naylor

I'm a live streamer, software engineer, and developer educator. I help developers build cool stuff with blog posts, tutorial videos, live coding and open source projects.

Related posts

8 Jul 2021

How I set up my new Next.js projects with a handy bash script

After I create a new Next.js application with npx create-next-app, I run this bash script to prepare my app for development — just the way I like it. And then I tell myself to have a nice day! Give it a try!

Next.js 1 min read →

1 Jul 2021

How to add Algolia InstantSearch to your Next.js application

By the time I had written 15 blog articles on my website, it was getting a little tricky to find what I was looking for in a hurry! So I set out to implement search functionality on my blog.

Tutorials 9 min read →