3

In webpack entry file index.js I'm just importing 2 CSS files a.css and b.css but it is not working because of b.css does not see variable from a.css: WARNING in b.css... variable --textColor is undefined and used without a fallback. How should I change webpack.config.js to get it work? I know I can directly import b.css in a.css but this is simple example, my project is much more complex with tens of CSS files and I do not want to change its content.

// 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);
}
mikep
  • 5,880
  • 2
  • 30
  • 37

1 Answers1

-1

First of all, @import will be deprecated soon. Use @use and @forward, so its worth to read about it.

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

postcss-css-variables You only need postcss-css-variables if you need support for legacy browser (ie11). otherwise just use the css-vars as they are. If you need legacy support I really recommend to build dual (for modern and one with transpiled css vars).

here's a legacy config for @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,
      },
    },
tfrei
  • 181
  • 1
  • 8