11ty / webc

Single File Web Components
MIT License
1.3k stars 36 forks source link

Minify CSS #203

Closed karolisgrinkevicius closed 3 months ago

karolisgrinkevicius commented 4 months ago

Hey there! 👋

Great extension. I love web components and the way it's incorporated into the 11ty. I have stumbled upon having my global styles (css) minified, is there any "best practice" approach already by any chance?

The following is my eleventy config:

import webcPlugin from '@11ty/eleventy-plugin-webc';

export default async function (config) {
  // Copy & minify styles
  // My global styles are served from src/_includes/assets/styles/global.css
  config.addPassthroughCopy('src/_includes/assets/styles', {
    transform: function (content, source, stats) {
      // Tried to return minified css here, no luck so far
  });

  // Add WebC plugin
  config.addPlugin(webcPlugin, {
    components: 'src/components/*.webc',
  });
}
karolisgrinkevicius commented 3 months ago

Hey there! 👋

After a few hours of exploration, I figured out the solution. I read the file contents with node within the provided transform option and resolve it through further. Don't be surprised about through2 dependency, it's strictly mandatory by recursive-copy utility which is the part of addPassthroughCopy.

import through from 'through2';

config.addPassthroughCopy('src/_includes/assets/styles/*.css', {
  transform: function (src) {
    return through(function (chunk, enc, done) {
      done(null, minifyCSS(fs.readFileSync(src, 'utf8')));
    });
  },
});

Please make sure you've got through2 installed beforehand.

npm i -D through2
karolisgrinkevicius commented 3 months ago

Closing this issue in the favour of already resolved solution. Please refer here for more details. 💪