16

How to avoid using relative path imports in Next.js

 3 years ago
source link: https://whitep4nth3r.com/blog/how-to-avoid-using-relative-path-imports-next-js
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
11 Jul 2021•1min 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.

whitep4nth3r | Salma Alam-Naylor

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK