1 min read

How to avoid using relative path imports in Next.js

Does this look familiar? 🤯

javascript
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.

json
{
  "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.

javascript
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.

A headshot of Salma wearing black on a red patterned background.

whitep4nth3r | Salma Alam-Naylor

I help developers build stuff, learn things, and love what they do • I code live on Twitch • DevRel • She/Her