【发布时间】:2020-11-28 02:17:18
【问题描述】:
大家好,
我想知道是否有办法以共享类名的方式链接 .scss。
这就是我想要实现的目标。
|- theme
| |- theme_default.scss
|- snippets
| |-componentA
| | |-componentA.js
| | |-componentA.scss
在 ComponentA.js 文件中,我使用 css-loader/CommonJS 将一个类从 ComponentA.scss 附加到组件(如果有人需要知道,我正在使用 webpack 开发环境)。
在theme_default.scss 中,我尝试将主题样式应用于“ComponentA”。默认主题文件应该可以被其他主题文件交换。
问题是类名(即使在源文件中相同)在编译成常规的“.css”文件时会被散列,这意味着主题 cssfile 中的类名永远不会匹配来自主题 css 文件的类名组件一个 cssfile。
那么我怎样才能明确主题文件应该使用与组件文件相同的类名而不将样式声明为global?我尝试在主题文件中使用@import 和@use,但它只复制规则,而类名仍然不相同。
欢迎任何意见,提前感谢阅读。
编辑
根据要求提供一些示例
theme_default.scss
.theme_default {
.comp_a /* This class should be the same (hashed) as in the componentA.scss */ {
background-color: red; /* awefull, but just for example sake */
}
}
组件A.scss
.comp_a {
display: flex;
flex-wrap: no-wrap;
/*.. etc.*/
}
componentA.js
import style from './componentA.scss'
// this is how I set the style, but this class does NOT know about any theme stylesheet. So nothing can be done from here
element.classList.add(style.comp_a);
为了应用主题,我将theme_default 类(哈希版本)设置为根元素,并让浏览器找出如何有效地(重新)呈现它。
我读到 css-loader 有一个带有compose(s) 的机制,它可能会解决这个问题。但它似乎不适用于 webpack 或 vsCode。所以无论如何有人需要它,这里是 webpack 配置文件中关于 css 处理的 sn-p。
webpack.configuration.js
{
test: /\.s[ac]ss$/i,
include: [
path.resolve(__dirname, 'src')
],
exclude: [
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, 'build'),
path.resolve(__dirname, 'test'),
],
use: [
// Creates `style` nodes from JS strings
isDevelopment ? 'style-loader' : MiniCssExtractPlugin.loader,
// Translates CSS into CommonJS
{
loader: 'css-loader',
options:
{
modules:
{
exportGlobals: true,
},
importLoaders: 2,
sourceMap: isDevelopment,
}
},
// Transform urls
{
loader: 'resolve-url-loader',
options:
{
sourceMap: isDevelopment
}
},
// Compiles Sass to CSS
{
loader: 'sass-loader',
options:
{
sassOptions:
{
indentWidth: 4,
sourceMap: isDevelopment,
sourceMapContents: false,
outputStyle: 'expanded'
},
},
}
],
},
【问题讨论】:
-
您能否举一个
theme_default.scss中的规则示例以及您如何使用ComponentA.js中的类名?我觉得这可能是一个与 CSS Modules/bundler 相关的问题,而不是 Sass -
@Coogan 这足以继续,还是您需要更多/其他信息?
-
我想是的。希望我能帮助你解决这个问题
标签: css webpack sass css-loader sass-loader