Import and @use from absolute paths in Next.JS

olaj

Ola Johansson

Posted on September 16, 2022

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

💖 💪 🙅 🚩
olaj
Ola Johansson

Posted on September 16, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related