EmbeddedSourceMapsPlugin.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Alexander Akait @alexander-akait
  4. */
  5. "use strict";
  6. const EmbeddedSourceMapsWarning = require("../errors/EmbeddedSourceMapsWarning");
  7. /** @import { PerformanceOptions } from "../../declarations/WebpackOptions" */
  8. /** @import Compiler from "../Compiler" */
  9. const PLUGIN_NAME = "EmbeddedSourceMapsPlugin";
  10. // The two families that put the map inside the bundle rather than beside it:
  11. // `eval` carries one per module, `inline` appends the whole map as a data url.
  12. const EMBEDS_MAP_REGEXP = /^eval|inline/;
  13. class EmbeddedSourceMapsPlugin {
  14. /**
  15. * Creates an instance of EmbeddedSourceMapsPlugin.
  16. * @param {PerformanceOptions} options the plugin options
  17. */
  18. constructor(options) {
  19. /** @type {PerformanceOptions["hints"]} */
  20. this.hints = options.hints;
  21. }
  22. /**
  23. * Applies the plugin by registering its hooks on the compiler.
  24. * @param {Compiler} compiler the compiler instance
  25. * @returns {void}
  26. */
  27. apply(compiler) {
  28. const hints = this.hints;
  29. if (!hints) return;
  30. const { devtool, mode } = compiler.options;
  31. // Only production: embedding is what these devtools are for everywhere
  32. // else, and the cost is only paid by the people loading the site.
  33. if (mode !== "production" || !devtool) return;
  34. // One devtool, or one per source type — either way it is the setting
  35. // that embeds which the report has to name.
  36. const embedding = (
  37. typeof devtool === "string" ? [devtool] : devtool.map((it) => it.use)
  38. ).find((it) => typeof it === "string" && EMBEDS_MAP_REGEXP.test(it));
  39. if (!embedding) return;
  40. compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
  41. // `afterSeal` is past the hash, which folds every message into it — a
  42. // hint reported earlier would change the build's identity.
  43. compilation.hooks.afterSeal.tap(PLUGIN_NAME, () => {
  44. const warning = new EmbeddedSourceMapsWarning(embedding);
  45. if (hints === "error") {
  46. compilation.errors.push(warning);
  47. } else if (hints === "stats") {
  48. compilation.hints.push(warning);
  49. } else {
  50. compilation.warnings.push(warning);
  51. }
  52. });
  53. });
  54. }
  55. }
  56. module.exports = EmbeddedSourceMapsPlugin;