繁体   English   中英

在 Next.js 应用程序中控制 CSS 模块的特异性

[英]Controlling the specificity of CSS Modules in a Next.js App

I'm trying to figure out a good workflow of how to use Tailwind together with CSS Modules in Next.js, but I'm running into some tricky problems regarding specificity and the order in which styles are inserted by Webpack.

考虑以下用例:我想创建一个可重用的 Button 组件,其 styles 可以被实用程序类覆盖。 选项 1是提取组件,如Tailwind Docs中所述:

/* button.jsx */

export const Button = props => <button {...props} className={`btn {props.className}`} />

在我的 tailwind.ZC7A62 tailwind.css文件中,我将在@layer指令中添加类名:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  .btn { @apply ... }
}

这很好,因为我可以使用实用程序类覆盖任何按钮 styles,因为它们具有更高的特异性。 但是,我在这里看到了一些小问题:

  • class 现在是全球性的,因此即使我不使用该组件,它也包含在每个页面中
  • 样式和组件不再位于同一位置 - 如果我创建许多这样的类,这可能会变得混乱

选项 2是使用 CSS 模块并应用如下类:

/* button.module.css */

.btn { @apply ...}
/* button.jsx */

import styles from "./button.module.css";

export const Button = props => <button {...props} className={`${styles.btn} {props.className}`} />

这样,CSS 仅在使用该组件时才被加载,并且 styles 位于同一位置。 这里的问题是在 Next.js CSS 模块是在全局 CSS 之后插入的,因此它们具有更高的特异性。 这完全有道理,通常我希望我的 CSS 模块能够覆盖全局 styles。 但是,在这种情况下,我希望将它们插入到我的全局 styles之前,以便我可以使用实用程序类覆盖它们。

我认为这应该可以通过调整 Webpack 配置来实现? 有谁精通 Webpack 知道如何做到这一点?

Go 用于第二个选项,只需添加! 使这一点变得重要。

/* button.module.css */

.btn { @apply !mb-0 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM