将 CSS 模块 kebab-case 类名转换为 Next.js 中的驼峰命名法

2024-03-09

我正在使用 CSS 模块(.scss)与 Next.js 并有一个 kebab 命名约定。换句话说,是这样的:

.member-btn {
    background: #fff;
}

我面临的问题是,为了使用它className我必须这样做styles["member-btn"]. E.g.

<Button className={styles["member-btn"]}>
    Hello world
</Button>

但是,我想将它与styles.memberBtn并像对象一样使用它(IDE​​ 也为此提供内置支持)。例如。

<Button className={styles.memberBtn}>Hello world</Button>

这在 Next.js 中可能吗?


Next.js 尚未提供一种简单的内置方法来自定义 CSS 模块选项(请参阅相关 RFCvercel/next.js#15818 https://github.com/vercel/next.js/discussions/15818)。这意味着你必须深入研究 webpack 并自定义css-loader由 Next.js 直接在您的next.config.js.

这是一个适用于最新 Next.js 版本的潜在解决方案,基于以下答案vercel/next.js#11267 https://github.com/vercel/next.js/discussions/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;
    }
}

这个想法是针对css-loader由 Next.js 内部使用并覆盖exportLocalsConvention选项'camelCase'。这使得可以使用驼峰命名的类名,例如styles.memberBtn.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 CSS 模块 kebab-case 类名转换为 Next.js 中的驼峰命名法 的相关文章

随机推荐