Next.js: Customizing the output format of CSS Modules classes

I'm a beginner with NextJS. I'm looking to update the CSS classes prefix + suffix to this new format:

<li class="desktop__menu-item--2feEH"></li>
<li class="desktop__menu-item--2feEH"></li>
<li class="desktop__menu-item--2feEH"></li>
<li class="desktop__menu-item--2feEH"></li>

Could someone please explain how to change the CSS classes in the component.module.css file to follow this new format:

[path][name]__[local]--[hash:base64:5]
?

Do I need to create a separate config.js file for this? My current setup is using Next.js v10.0.9.

Answer №1

Specifically for Next.js versions above 12

The solution provided is tailored for Next.js versions below 12.

const loaderUtils = require('loader-utils')

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
  )
}

/**
 * A function to generate context-aware class names during local development
 */
const localIdent = (loaderContext, localIdentName, localName, options) => {
  return (
    loaderUtils
      .interpolateName(loaderContext, btoa(unescape(encodeURIComponent(localName))), options)
      .replace(/\.module_/, '_') 
      .replace(/[^a-zA-Z0-9-_]/g, '_')
      .replace(/^(\d|--|-\d)/, '__$1')
  )
}

function cssLoaderOptions(modules) {
  const { getLocalIdent, ...others } = modules 
  return {
    ...others,
    getLocalIdent: localIdent,
    mode: 'local',
  }
}

const path = require('path')
module.exports = {
  webpack: config => {
    config.resolve.modules.push(path.resolve('./'))
    const oneOf = config.module.rules.find((rule) => typeof rule.oneOf === 'object')
   
    if (oneOf) {
      // Locate the module targeting *.scss|*.sass files
      const moduleSassRule = oneOf.oneOf.find(
        (rule) => regexEqual(rule.test, /\.module\.(scss|sass)$/)
      )
      
      if (moduleSassRule) {
        const cssLoader = moduleSassRule.use.find(
          ({ loader }) => loader.includes('css-loader')
        )
        
        if (cssLoader) {
          cssLoader.options = {
            ...cssLoader.options,
            modules: cssLoaderOptions(cssLoader.options.modules),
           
          }
        }
      }
    }

  return config

  },

  eslint: {
    ignoreDuringBuilds: true,
  }
}

Answer №2

Implementing custom css-loader options in Next.js

If you're looking to tweak the css-loader settings in Next.js, there isn't a direct method available yet.

But don't worry, you can still achieve this by delving into the webpack configuration within your next.config.js file. Simply navigate through each css-loader module loader and define the desired localIdentName.

// next.config.js

module.exports = {
    webpack: (config) => {
        const rules = config.module.rules
            .find((rule) => typeof rule.oneOf === 'object')
            .oneOf.filter((rule) => Array.isArray(rule.use));

        rules.forEach((rule) => {
            rule.use.forEach((moduleLoader) => {
                if (
                    moduleLoader.loader !== undefined &&
                    moduleLoader.loader.includes('css-loader') &&
                    typeof moduleLoader.options.modules === 'object'
                ) {
                    delete moduleLoader.options.modules.getLocalIdent;
                    moduleLoader.options = {
                        ...moduleLoader.options,
                        modules: {
                            ...moduleLoader.options.modules,
                            localIdentName: '[path][name]__[local]--[hash:base64:5]'
                            // You can also add other css-loader options here
                        }
                    };
                }
            });
        });

        return config;
    }
};

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

Reviewed and verified one package in 513 milliseconds with no vulnerabilities detected

After deleting my node_modules folder, as well as package.json and package-lock.json, I tried running npm install. Surprisingly, the response was: "up to date, audited 1 package in 513ms found 0 vulnerabilities", but no new node_modules were inst ...

Trouble displaying complete image (ReactJS, CSS)

I am looking to create a visually stunning landing page that covers the entire screen, showcasing a captivating image. However, I have encountered an issue where only a portion of the image is visible due to additional divs being created. Here is what my ...

Is there an issue with the second bootstrap navbar overlapping a dropdown-menu from the first navbar?

My issue involves two fixed-top navbars, where the dropdown-menu from the first one is being overlapped by the second navbar. I've tried adjusting z-index, positioning, and overflow properties without success. I have also looked at similar questions b ...

The addition and deletion of classes can sometimes lead to disruptions in the DOM

I've been struggling to phrase this question for a while now. I'm working on a single-page e-commerce site that operates by modifying the HTML in divs and using CSS along with JQuery to show and hide those divs. My problem arises when, occasional ...

Next.JS is having trouble importing the URL class from the 'url' module in Node

Recently, while developing with next.js and webpack 5, I encountered an issue where my URL class import stopped working unexpectedly. Upon running npm run build, the following error message appeared: Attempted import error: 'URL' is not export ...

Manually controlling line breaks in HTML text

When collaborating with designers, they often have strong opinions about word wrapping in the final HTML page. If I am working on a fixed layout (non-responsive) and the designer is not satisfied with how the text wraps, there are several options available ...

I can't understand why my body width is so disproportionately larger than usual

https://i.stack.imgur.com/jbeyI.png Encountering a new issue now. The width of my body is unusually high and I can't seem to identify the cause. I have included the code below. Tried adjusting margins but no luck. Searched for solutions online wi ...

I attempted to update the text on an HTML page using the content of "conetnt", however, it was unsuccessful

.custom-div { outline: none !important; width: 450px; margin: auto; background-color: #ccc !important; text-indent: -9999px;} .custom-div::before{content: 'sample';color: black;} ...

Customize your Material UI theme colors with SASS variables

I am exploring the idea of customizing the theme of Material UI in a dynamic way by incorporating SASS Variables that would update the Material UI theme automatically. When designing my page with Sass, I typically use variables to define colors: $primary ...

Typescript raises an issue regarding a React component's optional prop potentially being undefined

I have a basic React component that looks like this: interface ComponentProperties { onClick?: () => void; } const CustomComponent = (properties: ComponentProperties) => { if (!properties.onClick) { return <></>; } ...

Omit the use of "default" when importing a JSON file in Vite+React with Typescript

Each time I attempt to import a JSON file, it seems to enclose the JSON within a "default" object. When trying to access the object, an error message displays: Property 'default' does not exist on type... I have already configured resolveJsonMod ...

"Developing a stand-alone ASP.NET Core WebAPI with back-end authentication, and creating a React Redux application with front-end authentication that operate autonom

Looking to develop an ASP.NET Core Web API with authentication using ApplicationDbContext as the default database context. I prefer working with Visual Studio for the backend development. 2. Interested in building a React-Redux app with authentication for ...

Repeating linear gradients in the background

After creating a linear-gradient background animation in CSS for my to-do list, I encountered an issue. As I added more items to the list, the website became scrollable and the background started repeating, which made it look unappealing. I attempted to s ...

How to perfectly center an image vertically within a div using CSS

Seeking assistance to properly align images of different sizes in the center of a container div. Check out the attached image for reference, showcasing the gray background and the desired alignment of images in the middle. https://i.sstatic.net/M16V1.png ...

What steps are necessary to set up HTTPS on a standard nextjs application running on a Linux server?

Whenever I try to launch 'next start' on my Linux server, it only seems to be hosting on HTTP. Despite installing let's encrypt, I can't seem to figure out how to connect the certificate with the default next js server. I've heard ...

What could be the reason behind the occurrence of an invalid hook error when utilizing an imported function

I'm currently working on creating a navigation bar for a dashboard page, but I've run into an issue. Everything works fine until I try to integrate the navbar by importing and executing the function. I can pinpoint that the problem occurs when in ...

What could be the reason for my console not showing the unmount error in ReactJs?

I am currently enrolled in a MERN course where the instructor is demonstrating how to fetch movie data from the backend to a React app. Interestingly, when he logs out from the homepage, his console displays multiple errors; however, my console remains err ...

The hideCol method does not work on jqGrid

Encountering a problem with the hidecol method in jqGrid. Despite calling the method, nothing seems to happen. Using version 4.5 of jqGrid. The table is created as follows: // Table creation using jqGrid $('#shipTable').jqGrid({ data: tabl ...

The loading indicator fails to appear when navigating to a different page

I recently started using Next.js and have set up 3 pages: index.js categories/index.js categories/[slug].js To enhance the user experience, I decided to incorporate the library called NProgress, which displays a loading line at the top of the viewport wh ...

Tips for transferring simple CSS formatting to an independent stylesheet

As part of a university project, I am working on a basic website. Initially, I used in-line styling for the website design. However, the subject coordinator has now changed the requirements and we are only allowed to use an external CSS stylesheet. Most of ...