Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post CSS not converting custom properties

I have a project using Webpack that utilises PostCSS loader and code splitting. The CSS for modules is imported directly into entrypoints as per the below using SASS loader.

import '@/css/modules/components/_accordion.scss'

Some modules use CSS custom properties, which are declared in a separate module imported above in the same entrypoint.

import '@/js/modules/common'

This works fine, however, only the custom properties used in the common module get converted to hex values in compiled CSS as expected by PostCSS loader, not the ones used in each other SASS module subsequently imported into the entrypoint e.g. _accordion.scss.

As a workaround, in order for them to be converted I'm currently importing the file containing the custom properties at the top of each SASS module.

@import "css/tools/variables/colors";

This however means the custom property declarations are duplicated in multiple CSS files (chunks).

I would like a solution to avoid duplicating the declarations in the compiled CSS, while ensuring all custom properties are converted as expected by PostCSS.

like image 858
MrBizle Avatar asked Dec 06 '25 03:12

MrBizle


1 Answers

You need to add a PostCSS plugin to convert your CSS custom properties like postcss-preset-env

npm install css-loader postcss-loader postcss-preset-env --save-dev

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [ 'style-loader', 'postcss-loader' ]
      }
    ]
  }
}

postcss.config.js

module.exports = {
  plugins: {
    'postcss-preset-env': {},
  }
}

Of course, you could add any other loaders like Sass or Less in between.

References:

  • css-loader
  • postcss-loader
  • postcss-preset-env
like image 116
marcobiedermann Avatar answered Dec 07 '25 16:12

marcobiedermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!