DynamicEntryPlugin.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Naoyuki Kanezawa @nkzawa
  4. */
  5. "use strict";
  6. const EntryOptionPlugin = require("./EntryOptionPlugin");
  7. const EntryPlugin = require("./EntryPlugin");
  8. const EntryDependency = require("./dependencies/EntryDependency");
  9. /** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescriptionNormalized */
  10. /** @typedef {import("../declarations/WebpackOptions").EntryDynamicNormalized} EntryDynamic */
  11. /** @typedef {import("../declarations/WebpackOptions").EntryItem} EntryItem */
  12. /** @typedef {import("../declarations/WebpackOptions").EntryStaticNormalized} EntryStatic */
  13. /** @typedef {import("./Compiler")} Compiler */
  14. const PLUGIN_NAME = "DynamicEntryPlugin";
  15. class DynamicEntryPlugin {
  16. /**
  17. * @param {string} context the context path
  18. * @param {EntryDynamic} entry the entry value
  19. */
  20. constructor(context, entry) {
  21. this.context = context;
  22. this.entry = entry;
  23. }
  24. /**
  25. * Apply the plugin
  26. * @param {Compiler} compiler the compiler instance
  27. * @returns {void}
  28. */
  29. apply(compiler) {
  30. compiler.hooks.compilation.tap(
  31. PLUGIN_NAME,
  32. (compilation, { normalModuleFactory }) => {
  33. compilation.dependencyFactories.set(
  34. EntryDependency,
  35. normalModuleFactory
  36. );
  37. }
  38. );
  39. compiler.hooks.make.tapPromise(PLUGIN_NAME, compilation =>
  40. Promise.resolve(this.entry())
  41. .then(entry => {
  42. const promises = [];
  43. for (const name of Object.keys(entry)) {
  44. const desc = entry[name];
  45. const options = EntryOptionPlugin.entryDescriptionToOptions(
  46. compiler,
  47. name,
  48. desc
  49. );
  50. for (const entry of /** @type {NonNullable<EntryDescriptionNormalized["import"]>} */ (
  51. desc.import
  52. )) {
  53. promises.push(
  54. new Promise(
  55. /**
  56. * @param {(value?: undefined) => void} resolve resolve
  57. * @param {(reason?: Error) => void} reject reject
  58. */
  59. (resolve, reject) => {
  60. compilation.addEntry(
  61. this.context,
  62. EntryPlugin.createDependency(entry, options),
  63. options,
  64. err => {
  65. if (err) return reject(err);
  66. resolve();
  67. }
  68. );
  69. }
  70. )
  71. );
  72. }
  73. }
  74. return Promise.all(promises);
  75. })
  76. .then(x => {})
  77. );
  78. }
  79. }
  80. module.exports = DynamicEntryPlugin;