2
votes

So I want to use the benefits of CSSModules in a regular PHP project (a wordpress theme to be more specific). I am using webpack with autoprefixer, browsersync, postcss and more to compile and hot reload parts of the project while developing. I understand that there is also a plugin to postcss called postcss-modules which I would like to use.

The plugin is adding hashes to all my css classes and outputting a json with the mappings, as expected. Now I would like to bind one css module (which is a scss-file uncompiled) to each php file (as you would do when using css modules in React). How should I do this? I would still like the css to resist in one large file after compiling.

This is a part of my webpack config:

  {
    test: /\.(scss|css)$/,
    use: extractSass.extract({
      use: [{
        loader: "css-loader"
      },
      {
        loader: 'postcss-loader',
        options: {
          plugins: function () {
            return [
              require('precss'),
              require('autoprefixer'),
              require('cssnano'),
              require('postcss-modules')
            ];
          }
        }
      },
      {
        loader: "sass-loader"
      }],
      fallback: "style-loader"
    })
  },

And I am using a main.js and a style.scss as entry point in webpack. The style.scss is then importing all the partial scss-files (which should be one css module each).

1

1 Answers

3
votes

I did a really good writeup on how to do all this. The only difference is I am using grunt-postcss instead of Webpack to handle the postcss plugins and functionality. Should be straightforward to port the concepts over to Webpack.

The key is to configure postcss-modules to handle the separate pcss files as modules. That way you can parse the JSON separately per module. Using globalModulePaths you are able to keep your main pcss intact and append your modules to it.