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.

⚠️ This post is over two years old and may contain some outdated technical information. Please proceed with caution!

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.

Want weird stuff in your inbox?

Join undefined subscribers in the Weird Wide Web Hole to find no answers to questions you didn't know you had.

Subscribe

Salma sitting cross legged on a sofa, holding a microphone, looking up into the right of the space.

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 I run this bash script to prepare my app for development — just the way I like it. Give it a try!

Snippets 1 min read →

1 Jul 2021

How to add Algolia InstantSearch to your Next.js application

Every content website needs a search box.

Tutorials 9 min read →