In NextJS with SASS modules, the selector ":root" is considered impure since pure selectors are required to include at least one local class or id within them

Lately, I made the switch to using modules in my next.js project. However, I keep encountering an error in my newly created .module.scss files that says: "Selector ":root" is not pure (pure selectors must contain at least one local class or id)". It seems that the issue lies with the imports I am utilizing, particularly for variables like $cl-light-gray as shown below in this sample file:

@import "src/common/styles/global-styles.scss";
@import "node_modules/bootstrap/scss/bootstrap";
@import "src/common/styles/palette.scss";
@import "src/common/styles/typography.scss";

.dashboard-dropdown-hover {
  @extend .px-1;
  @extend .py-2;
  @extend .mt-3;
  border: 1px solid transparent;
  border-radius: 8px;
  transition: 200ms;
  background-color: transparent;
}
.dashboard-dropdown-hover:hover {
  background-color: $cl-light-gray;
}

If anyone knows a solution to resolving this import issue, I would greatly appreciate any guidance. While I understand reverting to .scss may solve the problem, I'm hesitant about importing all those .scss files in _app.tsx as it would entail around 30 imports and these styles are not meant to be global. Also, I am puzzled why Next.js insists on using pure css selectors when Sass, known for its non-pure elements, is being utilized.

Answer №1

After spending several hours researching online, I stumbled upon a fantastic solution at this link:

UPDATE: For those using Next.js 12, please refer to the end of the mentioned article as the solution may vary slightly.

To implement this solution, you will need to modify your next.config.js file with the following code snippet:

/** @type {import('next').NextConfig} */
require("dotenv").config();
const regexEqual = (x, y) => {
  return (
    x instanceof RegExp &&
    y instanceof RegExp &&
    x.source === y.source &&
    x.global === y.global &&
    x.ignoreCase === y.ignoreCase &&
    x.multiline === y.multiline
  );
};
// Customizations for css-loader plugin
function cssLoaderOptions(modules) {
  const { getLocalIdent, ...others } = modules; // Removing getLocalIdent is necessary for localIdentName functionality
  return {
    ...others,
    localIdentName: "[hash:base64:6]",
    exportLocalsConvention: "camelCaseOnly",
    mode: "local",
  };
}
module.exports = {
  webpack: (config) => {
    const oneOf = config.module.rules.find(
      (rule) => typeof rule.oneOf === "object"
    );
    if (oneOf) {
      // Locating the module targeting *.scss|*.sass files
      const moduleSassRule = oneOf.oneOf.find((rule) =>
        regexEqual(rule.test, /\.module\.(scss|sass)$/)
      );

      if (moduleSassRule) {
        // Retrieving the configuration object for css-loader plugin
        const cssLoader = moduleSassRule.use.find(({ loader }) =>
          loader.includes("css-loader")
        );
        if (cssLoader) {
          cssLoader.options = {
            ...cssLoader.options,
            modules: cssLoaderOptions(cssLoader.options.modules),
          };
        }
      }
    }
    return config;
  },
};

Although not an expert in webpack and its workings, I found success with this solution. You can also customize the regex pattern to include css by adding (scss|sass|css) if desired.

Answer №2

It has been highlighted here that there is an alternative approach: incorporating those styles into the global.css file. By following this method, Nextjs will function smoothly.

Answer №3

To ensure consistent styling across your entire app, including global styles like :root or specific HTML elements/CSS classes, it's recommended to place them in a dedicated global CSS file. This file should be imported into your _app.js component, which can be added to the root folder of your project if it doesn't already exist. Additionally, any fonts that will be used throughout the app should also be imported in this global CSS file.

For detailed step-by-step instructions on how to implement this, you can visit: https://nextjs.org/docs/basic-features/built-in-css-support

Answer №4

When faced with a similar issue, I discovered that the headache was due to my attempt to import a file using the path:

/node_modules/bootstrap/scss/bootstrap-utilities.scss

This file was then importing another file called _root.scss which had a selector defined in this style:

:root{

 }

To resolve this error, I opted to only import the specific files required for my project's needs.

If you're dealing with a similar problem, consider checking out these additional resources:

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

Vertically Center Image in a Div

I have been struggling to center an image within a div, but all the usual methods like using margin: auto; do not seem to work. I have tried various popular techniques with no success. <style> /* Add a black background color to the top navigation ...

Having trouble with showing dynamic data in column2 of my HTML layout, and the alignment doesn't look quite right in HTML

I'm working with this HTML file, attempting to create a two-column layout using HTML and CSS. I want one column to be labeled REQUEST and the other RESPONSE. When a value is entered in the text field in Column 1, it should display a response in Column ...

Is it possible to style an element that has extended beyond its parent container using CSS?

Is it possible to select items that have a float:right property and appear on the next line due to reasons like excessive content on the left or a window size too small? This is necessary because the parent item has a background image that looks good, but ...

Adjusting the gutter size for specific components in Bootstrap 4 using a mixin

How can I adjust the spacing between specific elements using mixins in my code? I've searched through numerous tutorials, but I haven't found the solution I'm seeking. Here is the code snippet I'm working with: <div class="row" id= ...

Ways to customize the background color of selected items in ion-list on Ionic

I am working on an Ionic project and I have a list of items. I am trying to change the background color of the pressed item. Can someone help me with this? index.html <ion-list> <ion-item ng-repeat="item in familleItems"> <div ng- ...

Insert between the top navigation bar and the sidebar menu

I am currently in the process of designing my very first website and I have encountered a bit of trouble. I would like to add a page between a navbar and a vertical bar, and I want this page to be displayed when a button on the vertical bar is clicked. You ...

Conceal a Component within an Embedded Frame

Hey there! I've been attempting to hide a header within an iframe, but it seems like my code isn't doing the trick. Could someone take a look and help me diagnose why the header is still visible? Thanks in advance! <iframe id="booking_iframe" ...

Can HTML tag attributes be accessed in CSS within the Shadow-DOM?

As I work on developing a custom component using StencilJS, I find myself needing to adjust the outline behavior when users navigate through it with either a keyboard or mouse. My component employs ShadowDOM and I aim to extract an HTML tag attribute from ...

Create a minimalist Vue table design that enforces a maximum of 2 or 3 columns within

Is there a way to make my v-simple table with v-chips and v-badges align correctly in two or three column peer cell format? Here is the table for reference: Currently, I only have scoped styling applied: <style scoped> .time-slot-x-small { border- ...

How to achieve a seamless iframe effect using CSS

With the introduction of new HTML5 iframe attributes, there are now more options available. One such attribute is the seamless attribute, which has the ability to: Create an iframe that appears to be seamlessly integrated into the containing document. ...

aligning two elements within a container to have equal heights

I need to position 2 divs inside a container div. Their height should always be the same, regardless of content. To achieve this, I am using absolute positioning with top and bottom set to 0. Currently, the container div #three collapses and hides the cont ...

Text fields do not show a cursor icon

On the website http://www.legrandclub.net, there are two text fields. Everything works fine in all web browsers except for Internet Explorer. When I click on one of the text fields, the cursor is not displayed, although it is possible to write text. What c ...

Is there a way to position text to the right of an image?

Looking for some help with aligning text to the right of an image within a hyperlink. I want the hyperlink to fill the rectangle and achieve a specific layout similar to attachment1, but currently getting something different like attachment2. If anyone ha ...

"Utilize PrimeNG's p-tabpanel to bind a unique style class to

When using the tabview component from PrimeNG, I am encountering an issue where I am unable to bind a header style class. Here is my static HTML code that works: <p-tabPanel header="Title" headerStyleClass="badge" formGroupName=&quo ...

"Troubleshoot: Why is the Position Absolute Not Functioning in

Trying to achieve a layout similar to the last element at the bottom of the footer] 1, but getting something like this instead: <footer> <div class="container-fluid"> <div class="row"> <div class="col-m ...

What are some techniques for applying CSS styling directly to a custom element?

Check out this amazing resource from HTML5 Rocks about the process of creating custom elements and styling them. To create a custom element, you can use the following code: var XFoo = document.registerElement('x-foo', { prototype: Object.crea ...

Implement a function that allows users to input a pin code digit by digit using a single HTML input

I am working on an application that requires users to input an SMS code for login. Below is a simplified example of what I need. For better accessibility, I want the SMS code input to be just one <input> in the HTML. I would also like to eliminate t ...

The text within my div is spilling over the edges despite my attempts to use text align and overflow properties

body { font-family: Arial; font-size: 15px; } .container { position: relative; max-width: 1800px; height: auto; margin: 0 auto; text-align: center; width: 90%; } .container img { vertical-align: center; } .container .content { pos ...

When employing dynamic URLs in Next.js, hot reloading may be compromised

Ever since I added [id].js to my Next.js dynamic URL, the hot reloading has stopped working. Even stopping npm and restarting it doesn't solve the issue. Does anyone have any insights on how to fix this? ...

Attempting to gather data from an HTML form and perform calculations on it using JavaScript

Looking for help with extracting user input from HTML and performing mathematical operations in JavaScript. Coming from a Python background, the variable system in JavaScript is confusing to me. Can someone provide guidance on how to achieve this? <div ...