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