Mastering the integration of Sass with NextJS

After successfully styling my NextJS app with SCSS modules, I encountered an unexpected error when I returned to work on it later:

Syntax error: Invalid CSS after "...ound: variables": expected expression (e.g. 1px, bold), was ".$main-gradient-bac"

I was puzzled because I hadn't made any changes since it was running smoothly before. Following the NextJS docs' recommendation, I installed SASS using npm i sass. The version of NextJS I am using is 9.5.1.

Here is a snippet from my package.json:

"scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "test": "jest"
  },
  "dependencies": {
    //dependencies here
  },
  "devDependencies": {
    //dev dependencies here
  }
}

The issue is not restricted to just one file as commenting out this particular file triggers errors in other .scss files as well:

@use 'variables';

html,
body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
  background: variables.$main-gradient-background;
  scroll-behavior: smooth;
}

a {
  color: lightseagreen;
  text-decoration: none;
}

button {
  background-color: black;
}

//more styles...

Answer №1

After some investigation, I discovered that the issue stemmed from node-sass. Once I removed it and installed sass instead, everything functioned as intended.

Answer №2

node-sass has been deprecated and will no longer be compatible with modern versions of nextjs

If you are in need of a solution for nextjs 11, I recommend checking out this repository, or diving into the full details provided in this article

Below is the complete next configuration code that I utilized:

const withTM = require('next-transpile-modules')([]);

const withPlugins = require('next-compose-plugins');

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = withPlugins([withTM], {
  reactStrictMode: true,
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    // Locate and remove NextJS css rules.
    const cssRulesIdx = config.module.rules.findIndex((r) => r.oneOf);
    if (cssRulesIdx === -1) {
      throw new Error('Could not find NextJS CSS rule to overwrite.');
    }
    config.module.rules.splice(cssRulesIdx, 1);

    // Add a simpler rule for global css anywhere.
    config.plugins.push(
      new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        // both options are optional
        filename: 'static/chunks/pages/[contenthash].css',
        chunkFilename: 'static/chunks/pages/[contenthash].css',
      }),
    );

    config.module.rules.push({
      test: /\.(sa|sc|c)ss$/i,
      use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
    });

    config.module.rules.push({
      test: /\.tsx/,
      use: [defaultLoaders.babel],
    });

    return config;
  },
});

Answer №3

To start using SASS in your project, make sure to first install the SASS library and then add the following code snippet to your next.config.js file:

const path = require('path')

module.exports = {
  sassOptions: {
    includePaths: [path.join(__dirname, 'styles')],
  },
}

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

Limitations of MaterialUI Slider

Looking for a solution to distribute 350 points across 8 sliders, each with a range of 0-100 and 5 marks at 0, 25, 50, 75, and 100. With each step consuming or returning 25 points, the challenge lies in allowing users to adjust the points allocation withou ...

The JSColor onChange event is throwing an error indicating that the function is not defined

When attempting to use the onChange event for JSColor to call a function, I consistently encounter an error indicating that the function is not defined. The code snippet below illustrates the issue: export class NavBar extends React.Component { constr ...

Utilizing the DirectusImage tag for a stylish background effect

I'm new to Directus and I need help styling a card with a background image from a Directus Image. Can anyone guide me on how to achieve this? Here's what I have tried: <Card style={{backgroundImage:"url({someColletion.image.id})" &g ...

What is the best way to retrieve the state value in react once it has been changed?

How can I ensure that the react state 'country' is immediately accessible after setting it in the code below? Currently, I am only able to access the previous state value in the 'country' variable. Is there a method such as a callback o ...

Can a custom cell editor for AG Grid be created using <input type="file"/>?

I need to create a custom cell editor for ReactJS AG Grid. You can find more information about AG Grid by following this link. Can I use an HTML file input to make this custom cell editor? <input type="file"> This way, users can select files such ...

The <main> element is not inheriting the height of its parent

https://i.sstatic.net/PchVf.png Using Chrome DevTools, I removed unnecessary elements from the DOM. The body is set to relative and takes up all available space in the document, which is exactly what I want. https://i.sstatic.net/AzELV.png My toolbar i ...

Changing the name of a React Native sample application

I am currently working on a project based on this App example: https://github.com/aksonov/react-native-router-flux/tree/master/Example When I tried to change the following lines: index.ios.js import App from './App'; AppRegistry.regist ...

displaying and concealing elements with jquery

Is there a way to hide a div if the screen size exceeds 700px, and only show it when the screen size is less than 700px? Below is the jQuery code I'm attempting to use: jQuery(document).ready(function() { if ((screen.width>701)) { $(" ...

When a user scrolls over an element with a data-attribute,

Looking to create a dynamic header effect on scroll? I have two headers, menu1 by default and menu2 hidden with display:none. In specific sections of my website, I've added a special attribute (data-ix="change-header") to trigger the header change. T ...

Switch between pages within a reactjs application by utilizing react router

Greetings! I am currently diving into the world of reactjs and experimenting with navigation from one page to another by simply clicking on a link through react router. In my home.js file, I have listed out some interesting places and I aim to click on one ...

Collaborate on sharing CSS and TypeScript code between multiple projects to

I am looking for a solution to efficiently share CSS and TS code across multiple Angular projects. Simply copy-pasting the code is not an ideal option. Is there a better way to achieve this? ...

Bootstrap for handling screen rotation and responsive design

Utilizing bootstrap to showcase canvas thumbnails within a div for lighter client-side creation. While not the perfect design, it's functional. An issue arises when viewing the app on a mobile device in portrait mode - the col-xs-6 class remains fixe ...

Could you explain the purpose of the usage section in a CodeMirror 6 language pack?

When you visit (for example) https://github.com/exercism/codemirror-lang-elixir?tab=readme-ov-file, you will see the following code snippet: import { StreamLanguage } from '@codemirror/language' import { elixir } from 'codemirror-lang-elixir ...

Handling null values in React with Typescript and GraphQL: best practices

Dealing with nullable fields in GraphQL queries can be tricky. When working with a large nested query, handling all the null values cleanly becomes a challenge... For example, consider the following GraphQL query: query { markdown { authors { ...

Guide on showcasing an alert notification when the data is already existing within an array through javascript

Need help with displaying an alert message in JavaScript for duplicate values in an array? var names = []; var nameInput = document.getElementById("txt1"); var messageBox = document.getElementById("display"); function insert() { names. ...

Comprehending the importance of a selector in a dropdown menu

Trying to figure out how to create a drop-down menu from CSS tricks, I found this code snippet: <nav role="navigation"> <ul> <li><a href="#">One</a></li> <li><a href="#"&g ...

mobile-responsive vertical alignment using Bootstrap

Here is a jsbin that demonstrates the issue and here is the markup: <div class="row"> <div class="col-sm-4 xs-12"> <strong>UK Postcode</strong> </div> <div class="col-sm-4 xs-12"> <strong>Other Fie ...

Output the name of the file while executing the ant process

Currently, I am utilizing YUI compressor within an ant build process to compress CSS and JavaScript files. I would like the compressor to display the name of each file it is processing as it goes along, so that in case of an error, I can easily pinpoint wh ...

Tips for dynamically appending a string to a predefined variable in React

When I was working on creating a text input space using the input type area and utilizing the onChange utility, everything was running smoothly. Now, my task is to incorporate an emoji bar and insert a specific emoji into the input space upon clicking it. ...

Tips for aligning pagination in the MUI v5 table component and creating a fixed column

I am currently experimenting with MUI table components and have created an example below with pagination. const MuiTable = () => { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [data, setData] ...