google / postcss-rename

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

Some CSS properties are broken when use postcss-rename #62

Closed RodrigoTomeES closed 1 year ago

RodrigoTomeES commented 1 year ago

Hi,

I am trying this postcss plugin with tailwind and I found that postcss-rename are broken some properties. I have a reproduction in this repo: https://github.com/RodrigoTomeES/awa-db/tree/feature/optimize-classes

To test it you only need:

yarn install
yarn build

In ./dist/_astro/ folder you can found the CSS file and in the root of the project should be has the file with the map.

You should see things like this:

@media (min-width: 768px) {
  .ub {
    t-template-columns: repeat(3, minmax(0, 1fr));
  }
  .vb {
    font-size: 3rem;
    line-height: 1.625;
  }
}

.O {
  s-radius: 0.35rem;
}
RodrigoTomeES commented 1 year ago

I think I found the issue, my script that process the HTML and JS files are also processing again CSS file.

import { readdir, readFile, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import prettyBytes from 'pretty-bytes';

const DIST_FOLDER = './dist/';
const MAP_FILE = './class-map.json';
const TARGET_FILES_EXT = ['.js', '.html'];

const classMap = JSON.parse(await readFile(MAP_FILE, 'utf8'));
const calculatePercent = (before, after) => (100 - (after / before) * 100) | 0;

async function* walkFiles(dir) {
  const dirents = await readdir(dir, { withFileTypes: true });

  for (const dirent of dirents) {
    const res = resolve(dir, dirent.name);

    if (dirent.isDirectory()) yield* walkFiles(res);
    else yield res;
  }
}

for await (const file of walkFiles(DIST_FOLDER)) {
  if (!TARGET_FILES_EXT.some((ext) => file.endsWith(ext))) continue;

  const fileName = file.split('dist')[1].replace(/\\/, '');
  let content = await readFile(file, 'utf-8');
  const oldSize = content.length;

  Object.keys(classMap).forEach((key) => {
    content = content.replaceAll(key, classMap[key]);
  });

  await writeFile(file, content);

  const newSize = content.length;
  const percent = calculatePercent(oldSize, newSize);

  // eslint-disable-next-line no-console
  console.info(
    `\u001b[32mProcessed: ${prettyBytes(
      newSize
    )} (reduced ${percent}% of original ${prettyBytes(
      oldSize
    )}) of ${fileName}.\u001b[39m`
  );
}

Some things are broken but I think is because the replaceAll is not the best strategy to parse the HTML and JS files. I will try with a regex an a exact match.