What is the process for disabling the CSS module feature in Next.js?

In Next.js, Global CSS can only be imported in _App.js. However, importing global CSS in every component is not allowed, so we have to use CSS modules to comply with this restriction imposed by Next.js.

Currently, I am in the process of migrating a large project to Next.js and converting the CSS of every module to CSS modules is proving to be quite challenging. Is there a way to bypass or remove this restriction?

For more information on this restriction, please refer to the documentation: https://nextjs.org/docs/messages/css-global

Answer №1

Answering this query on time is crucial. To customize the Webpack configuration, simply make edits to the next.config.js file as shown below:

const path = require('path');

const nextConfig = {
  webpack(config) {
    // If this doesn't work, try `config.module.rules[2]...`
    config.module.rules[3].oneOf.forEach((one) => {
      if (!`${one.issuer?.and}`.includes('_app')) return;
      one.issuer.and = [path.resolve(__dirname)];
    });
    return config;
  },
};

module.exports = nextConfig

For more information, refer to: How to Disable CSS Modules in Next.js

Answer №2

For some inexplicable reason, the solution provided by @vially kept causing the server to exit, even though it successfully identified the _app substring.

I made some slight modifications and managed to resolve my issue without having to guess the index anymore.

const path = require('path')

const nextConfig = {
  // other settings...
  webpack (config) {
    // iterate through all rules and locate those with `oneOf` key
    config.module.rules.forEach(rule => {
      if (!rule.oneOf) return

      rule.oneOf.forEach(one => {
        if (!`${one.issuer?.and}`.includes('_app')) return
        one.issuer.and = [path.resolve(__dirname)]
      })
    })
  },
}

module.exports = nextConfig

Alternatively, if you prefer not to continue searching after finding the substring, you can replace the main forEach with a for loop and keep track of success using a variable. Once the substring is found, update the variable and exit the loop.

const path = require('path')

const nextConfig = {
  // other settings...
  webpack (config) {
    let hasFound = false

    for (let i = 0; i < config.module.rules.length; i++) {
      const rule = config.module.rules[i]

      if (!rule.oneOf) continue

      rule.oneOf.forEach(one => {
        if (!`${one.issuer?.and}`.includes('_app')) return
        one.issuer.and = [path.resolve(__dirname)]
        hasFound = true
      })

      if (hasFound) break
    }
  },
}

module.exports = nextConfig

Answer №3

After searching on Medium, I have found a solution to your question.

const path = require('path');

module.exports = {
  webpack(config) {
    // If this code snippet doesn't work, try `config.module.rules[2]...`
    config.module.rules[3].oneOf.forEach((one) => {
      if (!`${one.issuer?.and}`.includes('_app')) return;
      one.issuer.and = [path.resolve(__dirname)];
    });
    return config;
  },
};

I hope this provided solution can assist you with your problem.

Answer №4

If you want to deactivate css-modules component styling in Next.js,

You can achieve this by adding the following configuration in your next.config.js:

/** @type {import('next').NextConfig} */
const path = require('path');
const nextConfig = {
  // disable css-modules component styling
  webpack(config) {
    config.module.rules.forEach((rule) => {
      const { oneOf } = rule;
      if (oneOf) {
        oneOf.forEach((one) => {
          if (!`${one.issuer?.and}`.includes('_app')) return;
          one.issuer.and = [path.resolve(__dirname)];
        });
      }
    })
    return config;
  },
}

module.exports = nextConfig

This method has been tested and verified for Next.js version: v12.3~v13.x

Answer №5

In the context of Next.js 13, I believe this approach offers a higher level of error protection:

optimize(config) {
    const styleRule = config.module.rules.find((rule) => rule.style);
    if (!styleRule) return console.log('Unable to locate css module rule to disable it');
    styleRule.style.forEach((style) => {
      if (!(style.generator && style.generator.or && `${style.generator.or}`.includes('_app'))) return;
      style.generator.or = [path.resolve(__dirname)];
    });
    return config;
  },

Answer №6

Consider eliminating any custom CSS configurations such as -@zeit/next-css -@zeit/next-sass from your next.config.js 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

Using console.log as an event listener

Check out this fiddle for reference: http://jsfiddle.net/calvintennant/jBh3A/ I am interested in utilizing console.log as an event listener: badButton.addEventListener('click', console.log); However, the fiddle demonstrates that this approach ...

Discovering and sorting an array in Vue.js based on IDs

Hello everyone, I've been attempting to filter my results using the filter and includes methods but it doesn't seem to be working. Does anyone have a solution for this, perhaps involving includes or something similar? companies ids [1,2,3] user c ...

ES6 promises: the art of connecting functions with parameters

Looking for a way to chain functions with delays? Here is an example of what I have tried: Promise.resolve() .then(setKeyframe('keyframe-0')) .then(delay(3000)) .then(setKeyframe('keyframe-1')) .then(delay(3000)) .then(setKeyframe(&apo ...

Troubleshooting Bootstrap bug caused by rollupPluginBabelHelpers

I am currently working on a Bootstrap 4 website. I noticed that in Internet Explorer, the modal works fine when opened for the first time, but then displays an error in the console and does not open when trying to do so a second time on the same window. On ...

Ways to show alternative data from a database in Laravel 8

I am working on a project where I need to display additional data based on the option selected from a dropdown menu populated from a database. Can anyone guide me on how to achieve this using javascript or jquery? https://i.stack.imgur.com/k3WLl.png Belo ...

Accessing form objects in Typescript with AngularJS

I am currently working with AngularJS and Typescript. I have encountered an issue while trying to access the form object. Here is the HTML snippet: <form name="myForm" novalidate> <label>First Name</label> <input type="text" ...

PHP is unable to decode JSON that has been converted from JavaScript

When I send an array as a POST request, I first convert it to JSON using the JSON.stringify() method. However, I encountered an issue when trying to decode it in PHP. // JavaScript var arr1 = ['a', 'b', 'c', 'd', & ...

A comprehensive guide on personalizing Bootstrap 4 tooltips to suit your specific needs

I would like to customize the tooltip in Bootstrap 4 based on the screenshot provided below: https://i.stack.imgur.com/wg4Wu.jpg <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta chars ...

How to retrieve an element using a dynamically generated class name in Vue.js

<v-data-table :headers="menuheaders" //this menus from api response :items="menus" item-key="usersmenu_menuid" items-per-page="1000" hide-default-footer="" class="elevation-1" > <template v-s ...

Overflow error in Rsuite table row cannot be displayed

Please see the image above Take a look at my picture. I am facing a similar issue. I am struggling to display my error tooltip over my table row. Has anyone else encountered this problem before? Any suggestions for me? I have attempted to set the overflow ...

I am facing a problem with the code for my React login page and router

My form page is built in react and typescript, utilizing JWT tokens on the API side. While there are no issues with the container page, I encountered an error on the index.tsx page where the routers are defined: A TypeScript error occurred in C:/Users/yusu ...

Creating a Modal Dialog with Justified Tab and Dropdown Using Bootstrap 4.1

I am struggling with Bootstrap 4.1 as I try to align content to the right side. Specifically, I have a Navigation Bar that triggers a Modal Dialog containing Tabs. The dropdown menu on the far right of the Tab is what I want to justify to the right. Here a ...

Enhancing live query functionality and providing a substitute for DOMNodeInserted specifically tailored for

I have searched multiple times on various platforms for a solution to my specific issue, but have not found one that fits my unique circumstances. My goal is to replace outdated code such as livequery and DOMNodeInserted. See examples below. I am current ...

Tips for integrating TypeScript with Vue.js and Single File Components

After extensive searching online, I have struggled to find a straightforward and up-to-date example of setting up Vue.js with TypeScript. The typical tutorials out there either are outdated or rely on specific configurations that don't apply universal ...

Angular app - static List mysteriously clears out upon refresh

My goal is to create a login page using Angular. I have an Angular component with HTML, CSS, and TypeScript files that manage this functionality. The HTML file contains two fields (Username and Password) and two buttons (Login and Register). When a user en ...

Calling a function within another function is not allowed in Typescript

Essentially, I have an Angular Web Page that uploads a file to the server via a POST request, which is then received by my NodeJS app. The issue arises when attempting to retrieve the file path in subirArchivo() and pass it to a function called InsertaPer ...

Ways to update the value within an object in an array stored in a BehaviorSubject?

My initial data is: const menuItems = [{id: 1, active: false}, {id: 2, active: false}] public menuSubject$ = new BehaviorSubject<MenuItem[]>(menuItems); public menu$ = this.menuSubject$.asObservable(); I am attempting to update the element with ...

Exploring ways to iterate through a Firestore array and retrieve data within a React Native environment

In my Firestore database, I have an array that contains categories of services. I want to display these categories when a user enters the details section. However, I encounter an error whenever I navigate to the Details Screen and attempt to map through t ...

Chart.js is failing to display the chart when integrated with RequireJS

I have been attempting to display a chart using Chartjs and Requirejs, but unfortunately, it is not rendering properly and no error messages are being displayed. I am aware that I may be overlooking something simple due to fatigue, but I am unable to pinpo ...

Double your audio experience with Webaudio by playing the sound twice

While working on WebAudio experimentation, I encountered an issue with loading a sound using the JavaScript code below. function playAudio(){ var audio = document.getElementById('music'); var audioContext = new webkitAudioContext(); ...