google / postcss-rename

Replace class names based on a customizable renaming scheme.
Apache License 2.0
125 stars 18 forks source link

pseudo element/class transformation? #69

Closed unleashit closed 5 months ago

unleashit commented 5 months ago

Hi, think I have a somewhat unusual use case in that I've written a small CLI to convert CSS modules into BEM (so users of a library can have a choice). It's working pretty well, except I still need it to transform some CSS module specific :global(.selector) pseudo elements which aren't legal in regular CSS.

So far the relevant part of the code is like this:

const camelToKebab = (str) =>
  str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();

const strategy = (selector) => {
  return `${camelToKebab(selector)}`;
};

async function main() {
  return await postcss([
    renamer({
      strategy,
      ids: true,
      prefix: `${prefix}${componentName}__`,
    }),
  ]).process(cssFile, { from: undefined });
}

main().then((o) => {
  fs.writeFileSync(newPath, o.css);
});

This works very well, unless the file contains any :global. Initially, I tried to add a regex in the strategy function, but noticed it doesn't receive the relevant pieces.

const strategy = (selector) => {
  const convertedCase =`${camelToKebab(selector)}`;

  // transform :global(.selector) to .selector
 return convertedCase.replace(/:global\((.+)\)/gm, ' $1');
};

Probably will just handle it manually if it can't be done and isn't worth adding as a feature.

nex3 commented 5 months ago

Yeah, I think this is something that's better handled as a separate plugin. This plugin is specifically for rewriting selector names, not doing generic selector rewrites.

unleashit commented 5 months ago

Thanks for the reply. It's actually a perfect fit for what I need it for. I'm in fact only rewriting selector names. The exception is :global (and actually :local too) elements because they are unique to CSS modules and need to be stripped out. If the api made either the full rule or the ignored parts available it would be possible, but I understand if you aren't interested.