Using Next.js, it is not possible to use absolute imports within SASS

Having trouble utilizing @/ imports within my scss files.

The variables I need are stored in src/styles/_variables.scss

Here is my tsconfig.json:

{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "baseUrl": ".",
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/": ["./src/"],
      "@/styles/": ["styles/"],
      "@/components/": ["components/"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

In my next.config.mjs file:

/** @type {import('next').NextConfig} */
const nextConfig = {
  sassOptions: {
    includePaths: [path.join(__dirname, "styles/")],
  },
};

export default nextConfig;

Struggling to troubleshoot this issue. Any insights would be greatly appreciated.

Seems like I've followed all the necessary steps to enable absolute imports in an .scss file, but it's not working as expected.

Answer №1

If you have a Sass file named _custom.scss where your custom styling variables are defined:

// _custom.scss

$primary-color: #ff6347;
$secondary-color: #20b2aa;
$font-family: 'Helvetica Neue', sans-serif;

Now, if you wish to utilize these variables in another Sass file, let's say main.scss:

// main.scss

@use 'custom';

body {
  font-family: custom.$font-family;
  background-color: custom.$primary-color;
}

h1 {
  color: custom.$secondary-color;
}

Make sure both files (_custom.scss and main.scss) reside in the same directory or verify that the path mentioned in the @use directive is accurate.

The @use directive allows us to import the _custom.scss file into our working file.

Answer №2

It's actually quite simple, all you need to do is define the variables you want in your _variables.scss file. For example:

$black: #000;
$white: #fff;
$gray: #f5f5f5;
$pink: #ff69b4;

Next, import the _variables in the .scss file where you want to use them. Make sure to import with the correct relative path. For instance, if your _variables file is located in src/styles/, you should import it using the complete relative path like this:

@import "src/styles/_variables.scss";
. Then simply utilize the variables in the file.

Example:

@import "src/styles/_variables.scss";

.main_example_class {
   background-color: $pink;
}

You can also opt for @use instead of @import. With @use, just call the file without the extension and underscore, then use the word variables before the variable name.

Example:

@use "src/styles/variables";

.main_example_class {
    background-color: variables.$pink;
}

I hope this explanation is helpful. The versions I am currently using are next.js 14.1.2 and sass ^1.72.0.

If you have any other queries, feel free to leave a comment and I'll assist you further.

PS: No additional configurations needed in next.config.mjs file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to assign a variable with the type (x:number)=>{y:number,z:number}?

I am trying to initialize a variable called foo, but my current code is not compiling successfully. let foo: (x: number) => {y:number,z: number} = (x) => {x+1, x+2}; This results in the following error: Left side of comma operator is unused and ha ...

Having trouble locating the name WebGLObject in my TypeScript code

Every time I try to run ng serve command An error pops up on my screen saying: "WebGLObject cannot be found." ...

The utilization of 'fs' in the getInitialProps function is not permitted

Running into an issue while trying to access the contents of a parsed file within getInitialProps when my view loads. The error message "Module not found: Can't resolve 'fs'" is being displayed, and this has left me puzzled - especially cons ...

Creating Angular models for complex nested JSON structures

I'm a beginner with Angular and I'm dealing with nested API responses from a Strapi application. I've set up a model using interfaces, but I'm having trouble accessing attributes from the product model when trying to access product data ...

What is the best strategy for managing a sizable react application using react-query?

Since diving into React with functional components and react-query, I've been facing some confusion on how to properly organize my components. Typically, I design components by having a top-level component handle all data access and pass data down to ...

Is there a method to retrieve Mui state classes easily?

One thing I really appreciate is the way to style mui-components with their class names. I'm curious if there's a method to access state classes like Mui-checked using a variable. Let me delve deeper into this: I have a styled component that lo ...

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

Recover data after a successful mutation using react-use-form, trpc, and prisma

Currently, I am working on a form that has a text input field for "title". After submitting the form, I can access the title property within the submit handler in my component like this: const formSubmit: SubmitHandler<FormSchemaType> = (formData) =& ...

Troubleshooting issue: Unable to locate library during testing with Nx, Jest, and Angular

In my nx monorepo, I have two apps (client, server) and 5 libraries (client-core, platform-core, etc). To include the libraries in the Angular client application, I set the paths in the tsconfig.json file. "paths": { "@myorg/platfo ...

Ways to rename a sequelize property following a join operation

I am encountering a problem with sequelize ORM. The data returned after joining has a nested object: { "id": 1, "username": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4125342e2f26252e282220 ...

Automatically signout of NextAuth.js if the Apollo GraphQL token is found to be invalid or has expired

Is there a recommended method for clearing the NextAuth.js session when encountering a 401 error in the Apollo GraphQL backend due to an expired or invalid token? I have considered using errorLink and signout, but I am aware that signout cannot be utilize ...

Ensure that NextJS <Link> obeys the standard "Redirects" middleware

I am currently using React and NextJS version 12, and I have a requirement to redirect the following two URLs: http://localhost:3000 http://localhost:3000/ Both of these URLs should be redirected to: http://localhost:3000/dashboard In order to achieve ...

Utilizing SASS to retrieve the H, S, L values from a color

Is there a way to extract the H, S, L values from a hex color in SASS and assign them to separate CSS variables? $colors: ( "primary": $primary, "secondary": $secondary) !default; :root { @each $color, $value in $colors { -- ...

What are the steps to implement vercel OG image in a folder of a next.js app?

I'm struggling to make ImageResponse work as a NextResponse. Specifically, I attempted to implement og image generation using @vercel/og within app/somedirectory/route.js. However, I encountered issues with implementing ImageResponse to be returned a ...

What is the best way to incorporate an image into the canvas element and then use it as a drawing surface?

I have been searching for solutions on various platforms, but I'm having trouble finding ones that work specifically with Ionic and Angular. One major issue I'm facing is trying to copy an image to the canvas. No matter what I try, I can't ...

Implementing Sass mixin transition to specifically add transition-delay - a comprehensive guide

As I continue to enhance my front-end development skills and practice Sass to optimize my CSS code, I encountered a roadblock. After exploring resources and tutorials online, I created a global mixin in Sass named 'transition'. Here is the code: ...

The property 'filter' is not recognized on the 'Object' type. An attempt to filter the response was made

Trying to fetch data from a JSON file that matches the player's name in the URL, such as localhost:4200/players/Febiven, should only retrieve information about Febiven. The code is written in Angular 6. The current code snippet is as follows: player ...

Employ gulp for rebasing CSS URLs

I have a question regarding how to resolve the following issue: In my sass files, I utilize absolute path variables in my main include files. For example, fonts are stored in /assets/fonts/... and icons are located in /assets/icons/... These paths only wo ...

Could you clarify the significance of the brackets in this TypeScript Lambda Expression?

I'm currently delving into an Angular book, but I'm struggling to locate any definitive documentation regarding the usage of square brackets in a lambda expression like [hours, rate]) => this.total = hours * rate. While I grasp that these para ...

What is the process for declaring a set in typescript?

In the documentation on basic types for Typescript, it explains using Arrays as a primitive type I am interested in the syntax: const numbers: string[] = [] How can I achieve the same with a set? ...