Import and @use from absolute paths in Next.JS
Ola Johansson
Posted on September 16, 2022
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";
that are really hard to copy-paste and also looks pretty ugly we can have this.
import colors from "@/css/colors.module.scss";
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/*"]
}
}
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/")],
},
}
and then you can go from
@use "../../css/colors.module.scss";
to
@use "colors.module.scss";
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
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
November 30, 2024