19

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.

3 Answers 3

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:

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Correct, it's currently transforming some CSS variables but not all of them as i've mentioned. Thanks for looking though
0

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

Webpack ExtractTextPlugin - avoid duplicate classes in output css

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.