Skip to main content

How to avoid using relative path imports in Next.js

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.

Read next πŸ‘‡

  • An icon of angled brackets with a forward slash in the middle.
  • A white triangle representing the Vercel logo.
A screenshot of the reset-next.sh gist in GitHub.

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

8 Jul 2021 1 min read

  • The pink Jamstack logo that features a blocked white J shape on a pink background.
  • A yellow square with the black letters JS at the bottom right.
  • The NodeJS logo in white, featuring the letters JS outlined by a hexagon.
  • An icon of a blank piece of paper with the bottom right corner turned up.
  • A white triangle representing the Vercel logo.
An illustration showing a web page, a magnifying glass, and the Next.js logo

How to add Algolia InstantSearch to your Next.js application

1 Jul 2021 9 min read

See all blog posts β†’