【问题标题】:How to handle global style transformations with postcss and webpack如何使用 postcss 和 webpack 处理全局样式转换
【发布时间】:2017-09-26 19:24:39
【问题描述】:

我使用 webpack2 和 postcss 来处理样式:

// webpack.config.js
rules: [{
    test: /\.sss$/,
    use: [
      'style-loader',
      {
        loader: 'css-loader',
        options: {
          modules: true,
          importLoaders: 1,
          camelCase: 'only',
          localIdentName: '[name]_[local]_[hash:base64:4]',
          sourceMap: true,
        },
      },
      'postcss-loader',
    ],
}]
// postcss.config.js
plugins: {
    'postcss-autoreset': {},
}

如果我有两个 .css 文件

/* a.css */
.a {
    padding: 20px;
}
/* b.css */
.b {
    background-color: red;
}

它们将被转换成类似这样的东西(为了清楚起见,我省略了 css-modules 的名称):

<style>
    /* transformed a.css content */
    .a {
        all: initial;
    }
    .a {
        padding: 20px;
    }
</style>

<style>
    /* transformed a.css content */
    .b {
        all: initial
    }
    .b {
        background-color: red;
    }
</style>

然后,如果我有 &lt;div class="a b"&gt;blah&lt;/div&gt; 之类的元素,则不会应用规则 padding: 20px;,因为为 .b 重置获胜。为了解决这个问题,所有的重置都应该像这样“提升”:

<style>
    .a,
    .b {
        all: initial;
    }
</style>

<style>
    .a {
        padding: 20px;
    }
</style>

<style>
    .b {
        background-color: red;
    }
</style>

这可能吗?

【问题讨论】:

    标签: webpack webpack-2 postcss


    【解决方案1】:

    似乎这更像是一个与postcss-autoreset 插件相关的“问题”。我从未使用过它,这是我第一次看到它,但在快速阅读 Docs 之后,您似乎可以传递一个规则选择器(支持正则表达式),使其有条件地通过此插件运行。
    例如:

    postcss([ require('postcss-autoreset')({
      rulesMatcher: (rule)=> rule.selector.match(/[.reset]/)
    })])  
    

    然后您可以使用.reset css 类来自动重置它们。

    【讨论】:

    • 其实我已经使用rulesMatcher选项了。它只过滤选择器将被重置,但我的问题是规则顺序,而不是过滤。我只想重置我所有的块和元素(在 BEM 的意义上)并期望它们“正常工作”,即使某些块和元素将混合在一个 dom 元素上
    猜你喜欢
    • 2020-06-28
    • 1970-01-01
    • 2019-10-21
    • 2017-12-02
    • 1970-01-01
    • 2018-09-05
    • 2023-03-08
    • 2020-02-29
    • 2018-05-01
    相关资源
    最近更新 更多