michalkvasnicak / babel-plugin-css-modules-transform

Extract css class names from required css module files, so we can render it on server.
MIT License
326 stars 54 forks source link

Better alternative #122

Open felixcatto opened 1 year ago

felixcatto commented 1 year ago

There is a better maintained version - babel-plugin-react-css-modules. With replaceImport: true option it does exactly what this plugin does. Also you can pass transform function to it and apply any postcss transforms.

babel.config.js

import postcss from 'postcss';
import nested from 'postcss-nested';
import crypto from 'crypto';

const generateScopedName = (localName, resourcePath, x) => {
  const getHash = value => crypto.createHash('sha256').update(value).digest('hex');
  const hash = getHash(`${resourcePath}${localName}`).slice(0, 4);
  return `${localName}--${hash}`;
};

const processPostcss = (cssSource, cssSourceFilePath) => {
  if (!cssSourceFilePath.endsWith('.module.css')) return '';
  return postcss([nested]).process(cssSource, { from: cssSourceFilePath });
};

export default {
  plugins: [
    [
      '@dr.pogodin/react-css-modules',
      {
        replaceImport: true,
        generateScopedName,
        transform: processPostcss,
      },
    ],
  ],
};