提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.2 KiB

  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("./Compiler")} Compiler */
  12. const PLUGIN_NAME = "DynamicEntryPlugin";
  13. class DynamicEntryPlugin {
  14. /**
  15. * @param {string} context the context path
  16. * @param {EntryDynamic} entry the entry value
  17. */
  18. constructor(context, entry) {
  19. this.context = context;
  20. this.entry = entry;
  21. }
  22. /**
  23. * Apply the plugin
  24. * @param {Compiler} compiler the compiler instance
  25. * @returns {void}
  26. */
  27. apply(compiler) {
  28. compiler.hooks.compilation.tap(
  29. PLUGIN_NAME,
  30. (compilation, { normalModuleFactory }) => {
  31. compilation.dependencyFactories.set(
  32. EntryDependency,
  33. normalModuleFactory
  34. );
  35. }
  36. );
  37. compiler.hooks.make.tapPromise(PLUGIN_NAME, (compilation) =>
  38. Promise.resolve(this.entry())
  39. .then((entry) => {
  40. const promises = [];
  41. for (const name of Object.keys(entry)) {
  42. const desc = entry[name];
  43. const options = EntryOptionPlugin.entryDescriptionToOptions(
  44. compiler,
  45. name,
  46. desc
  47. );
  48. for (const entry of /** @type {NonNullable<EntryDescriptionNormalized["import"]>} */ (
  49. desc.import
  50. )) {
  51. promises.push(
  52. new Promise(
  53. /**
  54. * @param {(value?: undefined) => void} resolve resolve
  55. * @param {(reason?: Error) => void} reject reject
  56. */
  57. (resolve, reject) => {
  58. compilation.addEntry(
  59. this.context,
  60. EntryPlugin.createDependency(entry, options),
  61. options,
  62. (err) => {
  63. if (err) return reject(err);
  64. resolve();
  65. }
  66. );
  67. }
  68. )
  69. );
  70. }
  71. }
  72. return Promise.all(promises);
  73. })
  74. .then(() => {})
  75. );
  76. }
  77. }
  78. module.exports = DynamicEntryPlugin;