modernweb-dev / web

Guides, tools and libraries for modern web development.
https://modern-web.dev
MIT License
2.16k stars 271 forks source link

[rollup-plugin-html] Expose `html-minifier-terser` options #2707

Open JulianCataldo opened 2 months ago

JulianCataldo commented 2 months ago

Hello,

I'm willing to open a PR for allowing finer control over HTML minification with @web/rollup-plugin-html.

Primary motivation for this feature, in my case, is preserving <!--lit-part EeTSS7FUtCM=--> comments in Declarative Shadow DOM (from Lit SSR output), thanks to the ignoreCustomComments matcher option.

But I'm sure some other peeps will find benefits by exposing the minifier API, versus a simple ON/OFF toggle.


Change:

if (pluginOptions.minify) {
  outputHtml = await minifyHTMLFunc(
    outputHtml,
    pluginOptions.minifyOptions
      ? pluginOptions.minifyOptions
      : {
          collapseWhitespace: true,
          removeComments: true,
          removeRedundantAttributes: true,
          removeScriptTypeAttributes: true,
          removeStyleLinkTypeAttributes: true,
          useShortDoctype: true,
          minifyCSS: true,
          minifyJS: true,
         // Or maybe with a spread here? Like `...pluginOptions.minifyOptions`
        },
  );
}

in: https://github.com/modernweb-dev/web/blob/efd8579cd12d578a742f8f5424ce0bbba36a7e72/packages/rollup-plugin-html/src/output/getOutputHTML.ts#L96-L107

Change:

import type { Options as HTMLMinifierOptions } from 'html-minifier-terser';

  /** Whether to minify the output HTML. */
  minify?: boolean;
  /** Minification options for HTML Minifier. */
  minifyOptions?: HTMLMinifierOptions;

Association types from @types/html-minifier-terser.

in:

https://github.com/modernweb-dev/web/blob/efd8579cd12d578a742f8f5424ce0bbba36a7e72/packages/rollup-plugin-html/src/RollupPluginHTMLOptions.ts#L13-L48


What do you think?

Thank you.

bashmish commented 2 months ago

I'd rather expose a way to override the minify function with a simple interface, seems like it fits well with the current design of the plugin. Can even be the same option set to a callback instead of a boolean:

pluginOptions.minify = (html) => {
  const minifiedHtml = /* process html */
  return minifiedHtml;
}