vikejs / vike

🔨 Flexible, lean, community-driven, dependable, fast Vite-based frontend framework.
https://vike.dev
MIT License
3.88k stars 334 forks source link

Apply Vite HTML transformers for SSG apps #389

Open brillout opened 1 year ago

brillout commented 1 year ago

Description

As explained in https://github.com/brillout/vite-plugin-ssr/issues/224, we cannot apply HTML transformers of Vite plugins for SSR apps.

That said, for SSG apps (i.e. pre-rendering all pages), we could apply HTML transformers.

Most notably:

kris7t commented 1 year ago

Quite a hacky solution, but I just wrote

import { readFile, writeFile } from 'node:fs/promises';

import fg from 'fast-glob';
import { minify } from 'html-minifier-terser';
import { green } from 'kolorist';

const filesToMinify = await fg('dist/client/**/*.html');

await Promise.all(filesToMinify.map(async (file) => {
  const html = await readFile(file, 'utf8');
  const minifiedHTML = await minify(html, {
    collapseBooleanAttributes: true,
    collapseWhitespace: true,
    removeComments: true,
    removeAttributeQuotes: true,
    removeRedundantAttributes: true,
    sortAttributes: true,
    sortClassName: true,
  });
  return writeFile(file, minifiedHTML, 'utf8');
}));

console.log(`${green(`✓`)} ${filesToMinify.length} HTML documents minified.`);

and set "build": "vite build && node minify.js" in the "scripts" section of package.json. This seems to work for transforming HTML files in SSG apps, since all HTML files should have been written to dist/client anyways.

Nevertheless, a proper way to support HTML transformation plugins would be nice, since as it currently stands, the HTML processing part has to be extracted from such plugins to be run manually.

schaschko commented 1 year ago

@kris7t ty, this was a great help to transform prerendered pages.

Would be a great enhancement if vite html transformation would work for vite-plugin-ssr imo.

For production when not all pages are prerendered this comment is very helpful (implement it in express). Also it's worth to notice that this can cause hydration issues, handle with care.

brillout commented 1 week ago

PR: https://github.com/vikejs/vike/pull/1678.