DEV Community

Ola Johansson
Ola Johansson

Posted on

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

Top comments (1)

Collapse
 
wwayne profile image
wwayne

Thanks for the sharing to solve my question :)