Search code examples
csswebpackpostcsscss-modules

Are where any examples available on how to use postcss-modules instead of css-modules?


CSS Modules support built into webpack looks pretty simple: you just require/import CSS file and webpack generate code that do two things:

  • Injects generated CSS into your webpage
  • Returns you a dictionary of classnames to use.

And the usage is pretty simple too:

import styles from "./style.css";
element.innerHTML = '<div class="' + styles.className + '">';

I want to test alternative CSS Modules implementation, a PostCSS plugin - since it seems to play well with other PostCSS plugins, especially autoprefixer. But according to official documentation it seems that postcss-modules works very differently compared to webpack CSS Modules. Where are no usage exaples in documentation and only some callback code that generates JSON. Any examples how it's used in practice to achieve same goal as sample code above?


Solution

  • I'm the author of the plugin. I'm rewriting it right now and right after that I'll write the example.

    In the callback, you can save the JSON object with the classes' description and read it into your code. You should read the JSON file, not the CSS:

    import styles from "./style.css.json";
    element.innerHTML = '<div class="' + styles.className + '">';