DllPlugin.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const FlagAllModulesAsUsedPlugin = require("../FlagAllModulesAsUsedPlugin");
  7. const DllEntryPlugin = require("./DllEntryPlugin");
  8. const LibManifestPlugin = require("./LibManifestPlugin");
  9. /**
  10. * @import {
  11. * DllPluginOptions
  12. * } from "../../declarations/plugins/dll/DllPlugin"
  13. */
  14. /** @import Compiler from "../Compiler" */
  15. /** @import { Entries, Options } from "./DllEntryPlugin" */
  16. const PLUGIN_NAME = "DllPlugin";
  17. class DllPlugin {
  18. /**
  19. * Creates an instance of DllPlugin.
  20. * @param {DllPluginOptions} options options object
  21. */
  22. constructor(options) {
  23. /** @type {DllPluginOptions} */
  24. this.options = options;
  25. }
  26. /**
  27. * Applies the plugin by registering its hooks on the compiler.
  28. * @param {Compiler} compiler the compiler instance
  29. * @returns {void}
  30. */
  31. apply(compiler) {
  32. compiler.hooks.validate.tap(PLUGIN_NAME, () => {
  33. compiler.validate(
  34. () => require("../../schemas/plugins/dll/DllPlugin.json"),
  35. this.options,
  36. {
  37. name: "Dll Plugin",
  38. baseDataPath: "options"
  39. },
  40. (options) =>
  41. require("../../schemas/plugins/dll/DllPlugin.check")(options)
  42. );
  43. });
  44. const entryOnly = this.options.entryOnly !== false;
  45. compiler.hooks.entryOption.tap(PLUGIN_NAME, (context, entry) => {
  46. if (typeof entry !== "function") {
  47. for (const name of Object.keys(entry)) {
  48. /** @type {Options} */
  49. const options = { name };
  50. new DllEntryPlugin(
  51. context,
  52. /** @type {Entries} */
  53. (entry[name].import),
  54. options
  55. ).apply(compiler);
  56. }
  57. } else {
  58. throw new Error(
  59. `${PLUGIN_NAME} doesn't support dynamic entry (function) yet`
  60. );
  61. }
  62. return true;
  63. });
  64. new LibManifestPlugin({ ...this.options, entryOnly }).apply(compiler);
  65. if (!entryOnly) {
  66. new FlagAllModulesAsUsedPlugin(PLUGIN_NAME).apply(compiler);
  67. compiler.hooks.compilation.tap(
  68. PLUGIN_NAME,
  69. (_compilation, { normalModuleFactory }) => {
  70. normalModuleFactory.hooks.module.tap(
  71. { name: PLUGIN_NAME, stage: 10 },
  72. (module) => {
  73. if (module.factoryMeta === undefined) {
  74. module.factoryMeta = {};
  75. }
  76. module.factoryMeta.sideEffectFree = false;
  77. return module;
  78. }
  79. );
  80. }
  81. );
  82. }
  83. }
  84. }
  85. module.exports = DllPlugin;