DEV Community

Ola Johansson
Ola Johansson

Posted on

1

Import and @use from absolute paths in Next.JS

I have ignored my relative paths imports in JS and for my Sass / Scss stuff for years. Today i finally decided to take a look and see how this could be solved.

Node / Typescript

So instead of having imports like

import colors from "../../css/colors.module.scss";

import colors from "../css/colors.module.scss";
Enter fullscreen mode Exit fullscreen mode

that are really hard to copy-paste and also looks pretty ugly we can have this.

import colors from "@/css/colors.module.scss";
Enter fullscreen mode Exit fullscreen mode

no matter where i am in the project. To fix this all you need is to add this to your tsconfig.js

  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/css/*": ["css/*"]
    }
   }
Enter fullscreen mode Exit fullscreen mode

Reference: Next.JS Documentation

For Scss @use / @import

And the same thing for Sass, all you have to add is

const path = require("path");
const moduleExports = {
  sassOptions: {
    includePaths: [path.join(__dirname, "css/")],
  },
}
Enter fullscreen mode Exit fullscreen mode

and then you can go from

@use "../../css/colors.module.scss";
Enter fullscreen mode Exit fullscreen mode

to

@use "colors.module.scss";
Enter fullscreen mode Exit fullscreen mode

The Sass version works a bit different since there you just add a "global path". It will always look in the "same path" first but then it will look in the global.

Reference: Stack Overflow

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (1)

Collapse
 
wwayne profile image
wwayne

Thanks for the sharing to solve my question :)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay