如何关闭Next.js中的CSS模块功能



Next.js只允许在_App.js中导入全局CSS。但我们不能在每个组件中导入全局CSS,因此我们必须根据Next.js的限制使用CSS模块。

现在我正在将一个大型项目迁移到Next.js,很难将每个模块的css转换为css模块有什么方法可以取消这个限制吗

限制单据链接:https://nextjs.org/docs/messages/css-global

我希望回答这个问题不会让我们迟到。实际上,您可以通过编辑next.config.js文件来篡改Webpack配置,如下所示:

const path = require('path');
const nextConfig = {
webpack(config) {
// if not 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

以下是参考:在Next.js项目中禁用CSS模块

由于一些不清楚的原因,@vially解决方案一直退出服务器,尽管它确实找到了_app子字符串。

因此,我稍微修改了一下,并解决了我的问题。此外,不要再猜测指数了。

const path = require('path')
const nextConfig = {
// other settings...
webpack (config) {
// loop over all rules and find the ones 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

或者,如果在找到子字符串后不想继续搜索,请将主forEach替换为for循环,并在变量中跟踪成功。找到子字符串后,更新变量,循环将退出。

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

我在media中搜索,找到了你问题的答案。

const path = require('path');
module.exports = {
webpack(config) {
// if not 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;
},
};

我希望这个答案能帮助你

要禁用Next.js中的css模块组件样式,

在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

在next.js版本中验证:v12.3~v13.x

对于Nextjs 13,我认为这个解决方案更安全:

webpack(config) {
const oneOfRule = config.module.rules.find((rule) => rule.oneOf);
if (!oneOfRule) return console.log('Unable to find css module rule to disabled it');
oneOfRule.oneOf.forEach((one) => {
if (!(one.issuer && one.issuer.and && `${one.issuer.and}`.includes('_app'))) return;
one.issuer.and = [path.resolve(__dirname)];
});
return config;
},

尝试删除自定义CSS配置,如-@zeit/next css-@zeit/next萨斯在您的next.config.js 中

最新更新