documentation on css-modules非常稀疏,所以我不确定我是否可以这样做。
This article说我使用normal
和error
状态设置按钮的方式如下:
.common { /* font-sizes, padding, border-radius */ }
.normal { composes: common; /* blue color, light blue background */ }
.error { composes: common; /* red color, light red background */ }
但我更喜欢这样写:
.common {
/* font-sizes, padding, border-radius */
&.normal { /* blue color, light blue background */ }
&.error { /* red color, light red background */ }
}
就像我一直做的那样,没有引入这种新的composes
语法。我认为如果我可以将它们嵌套在代码中,那么哪些样式构建在其他样式之上会更清楚。
但我不知道这会被css-modules导出什么?他们提供的唯一例子是简单的类名选择器。我不知道.common.normal
将被导出为什么,或.common > .normal ~ .strange
是什么?如果我使用css-modules,我基本上必须不使用任何类型的CSS选择器吗?
答案 0 :(得分:9)
.common {
/* font-sizes, padding, border-radius */
:global {
&.normal { /* blue color, light blue background */ }
&.error { /* red color, light red background */ }
}
}
这是我的解决方案。如果您使用styles.common
,则css将为:
.ramdomStrings {
/* I'm not sure if this exists, but it doesn't matter */
}
.ramdomStrings.normal { /* blue color, light blue background */ }
.randomStrings.error { /* red color, light red background */ }
答案 1 :(得分:3)
我也使用较少的css模块,但我不认为他们使用'&'的方式符合css模块的目标。根据我的理解,'composes'更类似于@import而不是&,而我只发现自己正在使用&对于伪类。
你绝对可以按照这里的方式做事,但是你不觉得有必要在HTML中同时指定'common'和'normal'类吗?在我看来,仅仅指定'normal'要好得多,让正常使用'compose'继承共享样式。
答案 2 :(得分:2)
如果你正在使用webpack加载器来获取css-modules,你可以使用postcss加载器并添加各种插件来获得你想要的行为。
例如" postcss-nested"插件,允许您编写嵌套规则。