html_minifier.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2022 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. /**
  5. * @fileoverview A small wrapper around
  6. * third_party/node/node_modules/html-minifier, allowing processing an explicit
  7. * list of input files, which is not supported by the built-in CLI of
  8. * html-minifier.
  9. */
  10. const minify =
  11. require(
  12. '../../third_party/node/node_modules/html-minifier/src/htmlminifier.js')
  13. .minify;
  14. const path = require('path');
  15. const fs = require('fs/promises');
  16. // Regex to extract the CSS contents out of the HTML string. It matches anything
  17. // that is wrapped by a '<style>...</style>' pair.
  18. const REGEX = /^<style>(?<content>[\s\S]+)<\/style>$/;
  19. async function processFile(inputFile, outputFile) {
  20. // Read file.
  21. let contents = await fs.readFile(inputFile, {encoding: 'utf8'});
  22. if (inputFile.endsWith('.css')) {
  23. // If this is a CSS file, wrap it with a <style> tag first, since
  24. // html-minifier only accepts HTML as input.
  25. contents = `<style>${contents}</style>`;
  26. }
  27. // Pass through html-minifier.
  28. let result = minify(contents, {
  29. removeComments: true,
  30. minifyCSS: true,
  31. });
  32. if (inputFile.endsWith('.css')) {
  33. // If this is a CSS file, remove the <style>...</style> wrapper that was
  34. // added above.
  35. const match = result.match(REGEX);
  36. result = match.groups['content'];
  37. }
  38. // Save result.
  39. await fs.mkdir(path.dirname(outputFile), {recursive: true});
  40. return fs.writeFile(outputFile, result, {enconding: 'utf8'});
  41. }
  42. function main() {
  43. const args = {
  44. inputDir: process.argv[2],
  45. outputDir: process.argv[3],
  46. inputFiles: process.argv.slice(4),
  47. }
  48. for (const f of args.inputFiles) {
  49. processFile(path.join(args.inputDir, f), path.join(args.outputDir, f));
  50. }
  51. }
  52. main();