我可以使用带有LESS +嵌套的css模块吗?

mpe*_*pen 14 less reactjs webpack css-modules

关于css-modules文档很稀疏,所以我不确定我是否可以这样做.

这篇文章说的是我用按钮设置样式的方式normal,error状态看起来像这样:

.common { /* font-sizes, padding, border-radius */ }
.normal { composes: common; /* blue color, light blue background */ }
.error { composes: common; /* red color, light red background */ }
Run Code Online (Sandbox Code Playgroud)

但我更喜欢这样写:

.common {
    /* font-sizes, padding, border-radius */
    &.normal { /* blue color, light blue background */ }
    &.error { /* red color, light red background */ }
}
Run Code Online (Sandbox Code Playgroud)

就像我一直做的那样,没有引入这种新composes语法.我认为如果我可以在代码中嵌套它们,哪些样式构建在其他样式之上更清楚.

但我不知道这将由css-modules导出什么?他们提供的唯一例子是简单的类名选择器.我不知道.common.normal将被导出为什么,或者什么.common > .normal ~ .strange?如果我使用css-modules,我基本上不必使用任何类型的CSS选择器吗?

Jas*_*eng 9

.common {
    /* font-sizes, padding, border-radius */
    :global {
        &.normal { /* blue color, light blue background */ }
        &.error { /* red color, light red background */ }
    }
}
Run Code Online (Sandbox Code Playgroud)

那是我的解决方案.如果你使用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 */ }
Run Code Online (Sandbox Code Playgroud)

  • `css-loader` 似乎不喜欢在 :global 范围中使用 & LESS 选择器使用 Webpack 4 / css-loader 2.1.1 编译时出现以下错误`模块构建失败(来自 ./node_modules/css-loader/dist/ cjs.js):错误: :global` 之后缺少空格 (2认同)

mik*_*aub 3

我也在 css 模块中使用 less,但我不认为他们使用 '&' 的方式符合 css 模块的目标。根据我的理解,“composes”与 @import 比 & 更相似,而且我发现自己只使用 & 来表示伪类。

您绝对可以按照此处的方式进行操作,但是您是否觉得必须在 HTML 中指定“common”类和“normal”类有点奇怪?我认为最好只指定“正常”,并让正常使用“撰写”继承共享样式。