我使用CSS模块(.scss)和Next.js,并有一个烤肉串命名约定。换句话说,类似这样的事情:
.member-btn {
background: #fff;
}我面临的问题是,为了在className中使用它,我必须像styles["member-btn"]一样这样做。例如。
<Button className={styles["member-btn"]}>
Hello world
</Button>但是,我想将它与styles.memberBtn一起使用,并将其作为一个对象使用(IDE还提供了内置支持)。例如。
<Button className={styles.memberBtn}>Hello world</Button>这在Next.js中是可能的吗?
发布于 2022-10-15 23:17:45
Next.js还没有提供一种简单、内置的方式来定制CSS模块选项(参见相关的RFC vercel/next.js#15818)。这意味着您必须深入了解webpack,并在您的css-loader中直接定制Next.js使用的next.config.js。
以下是一种基于Next.js中的答案的适用于最新vercel/next.js#11267版本的潜在解决方案。
// next.config.js
module.exports = {
// other existing configurations here...
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'
) {
moduleLoader.options = {
...moduleLoader.options,
modules: {
...moduleLoader.options.modules,
// This is where we allow camelCase class names
exportLocalsConvention: 'camelCase'
}
};
}
});
});
return config;
}
}这样做的目的是针对Next.js内部使用的Next.js,并将exportLocalsConvention选项覆盖到'camelCase'。这允许使用camelCased类名,例如styles.memberBtn。
发布于 2022-10-21 05:09:13
这就是解决我的问题的地方,它将所有css模块类名转换为camelCase。
// next.config.js
module.exports = {
webpack: (config) => {
// camelCase style names from css modules
config.module.rules
.find(({oneOf}) => !!oneOf).oneOf
.filter(({use}) => JSON.stringify(use)?.includes('css-loader'))
.reduce((acc, {use}) => acc.concat(use), [])
.forEach(({options}) => {
if (options.modules) {
options.modules.exportLocalsConvention = 'camelCase';
}
});
return config;
},
};https://stackoverflow.com/questions/74038400
复制相似问题