Post CSS not converting custom properties
Asked Answered
P

3

18

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.

Palpitation answered 15/5, 2019 at 10:49 Comment(0)
L
1

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:

Lelia answered 20/7, 2020 at 7:14 Comment(0)
G
0

You can try to use a CSS Custom Property preprocessor such as postcss-css-variables, postcss-custom-properties or postcss-simple-vars to transform your CSS variables into a static representation.

Getraer answered 19/5, 2019 at 18:28 Comment(1)
Correct, it's currently transforming some CSS variables but not all of them as i've mentioned. Thanks for looking thoughPalpitation
A
0

using css-loader does resolve the duplicates but for whatever the reason,

Webpack ExtractTextPlugin - avoid duplicate classes in output css

Alsace answered 24/5, 2019 at 4:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.