2

在 webpack 条目文件 index.js 中,我只是导入了 2 个 CSS 文件 a.css 和 b.css 但它不起作用,因为 b.css 看不到来自 a.css: 的变量WARNING in b.css... variable --textColor is undefined and used without a fallback。我应该如何更改 webpack.config.js 以使其正常工作?我知道我可以直接在 a.css 中导入 b.css 但这是一个简单的例子,我的项目要复杂得多,有数十个 CSS 文件,我不想更改它的内容。

// webpack.config.js

var MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = (env, options) => {
    return {
        entry : 'index.js',
        mode : 'development',
        output : {
            path : '/public',
        },
        plugins : [
            new MiniCssExtractPlugin(),
        ],
        module : {
            rules : [
                {
                    test : /\.css$/,
                    use : [
                        {
                            loader : MiniCssExtractPlugin.loader,
                        },
                        {
                            loader : 'css-loader',
                        },
                        {
                            loader : 'postcss-loader',
                            options : {
                                plugins: [
                                    require('postcss-css-variables')(),
                                ],
                            },
                        },
                    ],
                },
            ],
        },
    };
}
// index.js
import 'a.css';
import 'b.css';
// a.css
:root {
  --textColor: red
}
// b.css
body {
  color: var(--textColor);
}
4

1 回答 1

-1

首先,@import 将很快被弃用。使用@use 和@forward,因此值得一读。

https://sass-lang.com/documentation/at-rules/
使用 https://sass-lang.com/documentation/at-rules/forward

postcss-css -variables 如果您需要对旧版浏览器 (ie11) 的支持,您只需要 postcss-css-variables。否则,只需按原样使用 css-vars。如果您需要旧版支持,我真的建议您构建双重(对于现代和带有转译 css vars 的)。

这是@import 的旧配置

    {
      // snippet from
      // https://github.com/unic/darvin-webpack-boilerplate/blob/master/webpack/settings/style-legacy/index.js#L29
      loader: 'postcss-loader',
      options: {
        plugins: () => [
          autoprefixer({
            grid: 'autoplace',
            flexbox: 'no-2009'
          }),
          require('postcss-css-variables')({ preserve : false, preserveAtRulesOrder: true })
        ],
        sourceMap: false,
      },
    },
于 2020-06-09T16:37:03.353 回答