ig22
ig22

Reputation: 11

Issues with NextJs 14.2 (app router) and global scss file

I am new to NextJs. I recently created a new project and was looking throught the documentation to see how to set it up correctly. There, I saw that I basically have a layout.tsx component that imports a global.css file, which is accessible throughout the application.

Since I've been using sass for a while now, I figured I would follow the steps to use it in my Next app. So I installed the npm package and changed my /src/app/global.css and /src/app/page.module.css files extensions to scss. After trying to set global variables I found they were not accessible in other pages.

I would get: SassError: Undefined variable $x

I thought that maybe this was related to the scoped nature of the .module.css files but after reverting back to the original state and creating css variables in global.css file:

:root {
  --x: #FFFFFF;
} 

I found they are accessible in other style files, for instance page.module.css:

.main {
  background-color: var(--x);
}

What am I missing here? I think the documentation is not clear in this regard and haven't been able to find solutions online.

Thanks for helping out!

Upvotes: 1

Views: 1023

Answers (2)

GMKHussain
GMKHussain

Reputation: 4691

/* variables.module.css */

$x: #64ff00;
 
:export {
  myVariable: $x;
}

Usage in another CSS file

@import './variables.css';

.example {
  color: var(--myVariable);
}

Usage in JS file

import variables from './variables.module.scss'
 
export default function MyComponent() {
  return <h1 style={{ color: variables.myVariable }}>My Content</h1>
}

Upvotes: 0

MHD Alaa Alhaj
MHD Alaa Alhaj

Reputation: 3213

Unlike CSS, SCSS variables need to be exported.

Next.js supports Sass variables exported from CSS Module files.

$x: #64ff00;
 
:export {
  myVariable: $x;
}

Then to use it:

import variables from './variables.module.scss'
 
export default function Page() {
  return <h1 style={{ color: variables.myVariable }}>Hello, Next.js!</h1>
}

Upvotes: 1

Related Questions