Unleashing the power of Sass and CSS in your Next Js project

Trying to incorporate sass and css modules into my next.config.js has been challenging due to an error I keep encountering:

Failed to compile.

./node_modules/@riskalyze/react-ui/node_modules/@riskalyze/calendar/assets/index.css
Unknown word (1:1)

> 1 | var api = require("!../../../../../../style-loader/dist/runtime/injectStylesIntoStyleTag.js");
    | ^
  2 |             var content = require("!!../../../../../../css-loader/index.js!./index.css");
  3 | 
  4 |             content = content.__esModule ? content.default : content;

After researching on github and stackoverflow, it seems like the issue stems from having two instances of css module configurations in my next.config.js. However, I am unsure how to consolidate them while preserving the logic:

      config.module.rules.push({
        test: /\.css$/,
        use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
      });

Here is the full version of my next.config.js file:

const path = require('path');
const withSass = require('@zeit/next-sass');
const withCSS = require('@zeit/next-css');

const aliasPathsToResolve = [
  {
    name: 'react-ui',
    path: path.resolve(__dirname, './node_modules/@riskalyze/react-ui/')
  },
  {
    name: '@babel/runtime-corejs2',
    path: path.resolve(__dirname, './node_modules/@babel/runtime-corejs2/')
  }
];

module.exports = withCSS(
  withSass({
    cssModules: true,
    cssLoaderOptions: {
      importLoaders: 1,
      localIdentName: '[name]__[local]___[hash:base64:5]'
    },
    webpack: (config, { defaultLoaders }) => {
      config.module.rules.push({
        test: /\.+(js|jsx|ts|tsx)$/,
        loader: defaultLoaders.babel,
        include: /react-ui/
      });

      config.module.rules.push({
        test: /\.css$/,
        use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
      });

      aliasPathsToResolve.forEach(module => {
        config.resolve.alias[module.name] = module.path;
      });

      return config;
    }
  })
);

Answer №1

If you're working on a Next.js project, incorporating Sass is easy thanks to the built-in support for it.

There's no need for complex configurations - simply install the Sass package:

npm i sass

Next.js will recognize the Sass dependency and activate the built-in Sass loader automatically.

To apply global styles, you can make use of /pages/_app.js.

When it comes to component-specific or page-specific Sass files, utilize the CSS modules' built-in functionality.

For instance, if you have a component named Button.js, you can create a Sass file called button.module.scss and link it to the component.

Learn more about Adding Component-Level CSS here.

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

Not implementing auto-scroll feature because of the presence of `position: sticky` or `position: fixed` CSS properties

I'm encountering a console warning while working on my Nextjs project. Here is the snippet of my code: <aside className={`site-off desktop-hide ${showMenu ? "show-menu" : ""}`}> .... </aside> And here is the relevant ...

Pressing the button does not switch the component state (when the button and component are located in separate files)

Here is the code snippet of my layout: import Menu from "./Menu"; import ButtonMenu from "./ButtonMenu"; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en" ...

Potential prefetching issue encountered when using react-router with NextJS

Encountered an error while attempting to prefetch the data react_query__WEBPACK_IMPORTED_MODULE_5__.QueryClient.prefetchQuery is not a function Here is my code snippet: const formReducer = (state, event) => { return { ...state, [event.target ...

When the width is reduced to a certain point, the display will change to inline-block, preserving the layout structure

My goal is to maintain a two-column layout for my container boxes, even when the browser width is minimized to 600px in my fiddle. The issue arises with the CSS rule display: inline-block causing the boxes to stack into a single column. Important point: I ...

Using jQuery to add or remove multiple classes at once

My navigation tabs use jQuery to add and remove classes for the active tab. However, I'm facing an issue where the active class is not removed when a new tab is clicked or when the user scrolls to a new section. Please refer to the following gist for ...

The side menu in Bootstrap dropdown experiences a one-time functionality

When navigating through a responsive top menu with Bootstrap, everything works seamlessly - from toggling the menu to dropdown functionality. However, I encountered an issue with the side menu as nav-pills used to select tab-panes. <div class="containe ...

Link SQL Server and Next.js for seamless data integration

Encountering a pesky issue (ConnectionError) when attempting to connect Next.js with SQL Server using mssql, I have already made sure that TCP/IP is enabled and the SQL Server Browser is up and running. Here is the code snippet causing the problem: // db. ...

NodeJS is facing a severe challenge in properly rendering HTML and its accompanying CSS code, causing a major

Once upon a time, I built a beautiful website while practicing HTML, CSS, and JS. It had multiple web pages and used Express for the backend. Unfortunately, I lost all the files associated with it and took a break from web programming for some time. Now, w ...

What is the most efficient way to access a cell within an HTML table using jQuery or the Document Object Model (

I have an unchangeable HTML table styled with CSS. My goal is to extract the value from the first column for filtering purposes. I've been struggling to locate a suitable jQuery or DOM function to accomplish this task. Unable to find a way to access ...

Bootstrap select box gracefully fits within a dynamically adjusting height div

Can someone help me troubleshoot the issue with displaying/overflowing the .drop-down outside of the .item box in this demo? I need to keep the height of the .item as auto but for some reason, I can't enable overflow visible on it. .item{ backg ...

Shiny Chrome, Flexible Flexbox, and plump div elements

Looking to enhance my understanding of flexbox. Encountering a display issue in Chrome where the right column is too wide and the left column is too skinny, while it displays correctly in Firefox. Any suggestions on how to fix this for Chrome? .child ...

The vertical scrolling feature seems to be malfunctioning within my angular 10 application

I'm having an issue with the scrollbar not working on this Angular 10 template, even after adding the CSS style overflow: auto; to the main container. Although I've included the overflow property in the main container "cont" as shown in the HTML ...

`How can a user be redirected in the Server component of Nextjs version 13?`

I'm a beginner with next js and looking for ways to redirect a user from a server component without relying on the "use client" method ...

The issue with hiding and showing elements using JavaScript during drag and drop functionality

In my code, I have two boxes with IDs box1 and box2, These boxes can be dragged and dropped into the boxleft element, Upon dropping them, the background image is removed and only the name appears in the box, My issue is that when loading values into box ...

Encountering an Error 404 while trying to access an API endpoint in Next.js version 14

I scoured articles and YouTube tutorials in search of a solution to the error 404 I encountered when trying to call an API router such as /api/hello/ Despite consulting the documentation on Next.js website, I couldn't find a fix for this issue. I eve ...

How are the number of Zeit serverless functions determined?

After migrating my Nextjs project to the Zeit platform and setting up the environment, I encountered deployment issues. The configuration is basic: { "version": 2, "name": "<....>", "alias": "<...>", "routes": [ { "src": "^/service ...

The text element does not line up with the icons

As I'm working on creating my first account page header, I've run into an issue with some of the icons not aligning perfectly with the text. While advanced developers may find this task simple, as a beginner, I could really use some advice on how ...

How can I modify the table structure in Ruby on Rails?

Greetings! I am a beginner in the world of Rails and could really use some assistance. Below is the table data extracted from index.html.erb: <table class="table"> <thead> <tr> <th>Area& ...

Having trouble getting CSS "::Before" to work in my HTML code - any solutions?

I've been struggling to make use of the ::before pseudo-element in CSS for a hover effect. Despite going through various tutorials on YouTube, I can't seem to get it to work properly. I'm not sure why this isn't working as expected. ...

Adaptive website backdrop

I have created a unique background for my website design, which includes 3 slices labeled as div id top, middle, and bottom. You can view the design in this image. I am interested in making this background responsive. While I have come across examples of ...