Search code examples
webpacknext.jscss-modules

How to disable css module file suffix ".module" in Next.js config?


I use css modules in 100% of cases, so why write the word .module in the file name every time? If I were manually configuring webpack I would change this suffix, but how do I do it in next.js?


Solution

  • I struggled with same problem and after a few hours, I found a solution. If you want to use css-modules in 100 % cases, you must edit webpack config in your next.config.js:

    I did is by this code:

    const isTwoRegexEqual = (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
       );
    }
    
    const getConfigToAcceptSassFilesWithoutModuleSuffix = (config) => {
       return {
          ...config,
          module: {
             ...config.module,
             rules: config.module.rules.map((rule) => {
                if (rule.oneOf) {
                   return {
                      ...rule,
                      oneOf: rule.oneOf.map((loaderSettings) => {
                         if (
                            (!Array.isArray(loaderSettings.test) && isTwoRegexEqual(loaderSettings.test, /\.module\.(scss|sass)$/))
                            || (Array.isArray(loaderSettings.test) && loaderSettings.test.filter((test) => isTwoRegexEqual(test, /(?<!\.module)\.(scss|sass)$/ )).length > 0)
                         ) {
                            return {
                               ...loaderSettings,
                               test: /\.(scss|sass)$/,
                            }
                         }
    
                         return loaderSettings;
                      })
                   }
                }
                return rule;
             })
          }
       }
    };