transformUtils.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.transformIndexHtml = exports.injectScriptToHtml = exports.asyncReplace = void 0;
  4. async function asyncReplace(input, re, replacer) {
  5. let match;
  6. let remaining = input;
  7. let rewritten = '';
  8. while ((match = re.exec(remaining))) {
  9. rewritten += remaining.slice(0, match.index);
  10. rewritten += await replacer(match);
  11. remaining = remaining.slice(match.index + match[0].length);
  12. }
  13. rewritten += remaining;
  14. return rewritten;
  15. }
  16. exports.asyncReplace = asyncReplace;
  17. const injectReplaceRE = [/<head>/, /<!doctype html>/i];
  18. function injectScriptToHtml(html, script) {
  19. // inject after head or doctype
  20. for (const re of injectReplaceRE) {
  21. if (re.test(html)) {
  22. return html.replace(re, `$&${script}`);
  23. }
  24. }
  25. // if no <head> tag or doctype is present, just prepend
  26. return script + html;
  27. }
  28. exports.injectScriptToHtml = injectScriptToHtml;
  29. async function transformIndexHtml(html, transforms = [], apply, isBuild = false) {
  30. const trans = transforms
  31. .map((t) => {
  32. return typeof t === 'function' && apply === 'post'
  33. ? t
  34. : t.apply === apply
  35. ? t.transform
  36. : undefined;
  37. })
  38. .filter(Boolean);
  39. let code = html;
  40. for (const transform of trans) {
  41. code = await transform({ isBuild, code });
  42. }
  43. return code;
  44. }
  45. exports.transformIndexHtml = transformIndexHtml;
  46. //# sourceMappingURL=transformUtils.js.map