ModuleLibraryPlugin.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { ConcatSource } = require("webpack-sources");
  7. const RuntimeGlobals = require("../RuntimeGlobals");
  8. const Template = require("../Template");
  9. const ConcatenatedModule = require("../optimize/ConcatenatedModule");
  10. const propertyAccess = require("../util/propertyAccess");
  11. const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
  12. /** @typedef {import("webpack-sources").Source} Source */
  13. /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
  14. /** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
  15. /** @typedef {import("../Chunk")} Chunk */
  16. /** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */
  17. /** @typedef {import("../Compiler")} Compiler */
  18. /** @typedef {import("../Module")} Module */
  19. /** @typedef {import("../Module").BuildMeta} BuildMeta */
  20. /** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */
  21. /** @typedef {import("../util/Hash")} Hash */
  22. /**
  23. * @template T
  24. * @typedef {import("./AbstractLibraryPlugin").LibraryContext<T>} LibraryContext<T>
  25. */
  26. /**
  27. * @typedef {object} ModuleLibraryPluginOptions
  28. * @property {LibraryType} type
  29. */
  30. /**
  31. * @typedef {object} ModuleLibraryPluginParsed
  32. * @property {string} name
  33. * @property {string | string[]=} export
  34. */
  35. /**
  36. * @typedef {ModuleLibraryPluginParsed} T
  37. * @extends {AbstractLibraryPlugin<ModuleLibraryPluginParsed>}
  38. */
  39. class ModuleLibraryPlugin extends AbstractLibraryPlugin {
  40. /**
  41. * @param {ModuleLibraryPluginOptions} options the plugin options
  42. */
  43. constructor(options) {
  44. super({
  45. pluginName: "ModuleLibraryPlugin",
  46. type: options.type
  47. });
  48. }
  49. /**
  50. * Apply the plugin
  51. * @param {Compiler} compiler the compiler instance
  52. * @returns {void}
  53. */
  54. apply(compiler) {
  55. super.apply(compiler);
  56. compiler.hooks.compilation.tap("ModernModuleLibraryPlugin", compilation => {
  57. const { exportsDefinitions } =
  58. ConcatenatedModule.getCompilationHooks(compilation);
  59. exportsDefinitions.tap(
  60. "ModernModuleLibraryPlugin",
  61. (definitions, module) => {
  62. // If we have connections not all modules were concatenated, so we need the wrapper
  63. const connections =
  64. compilation.moduleGraph.getIncomingConnections(module);
  65. for (const connection of connections) {
  66. if (connection.originModule) {
  67. return false;
  68. }
  69. }
  70. // Runtime and splitting chunks now requires the wrapper too
  71. for (const chunk of compilation.chunkGraph.getModuleChunksIterable(
  72. module
  73. )) {
  74. if (!chunk.hasRuntime()) {
  75. return false;
  76. }
  77. }
  78. return true;
  79. }
  80. );
  81. });
  82. }
  83. /**
  84. * @param {LibraryOptions} library normalized library option
  85. * @returns {T | false} preprocess as needed by overriding
  86. */
  87. parseOptions(library) {
  88. const { name } = library;
  89. if (name) {
  90. throw new Error(
  91. `Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
  92. );
  93. }
  94. const _name = /** @type {string} */ (name);
  95. return {
  96. name: _name,
  97. export: library.export
  98. };
  99. }
  100. /**
  101. * @param {Source} source source
  102. * @param {Module} module module
  103. * @param {StartupRenderContext} renderContext render context
  104. * @param {LibraryContext<T>} libraryContext context
  105. * @returns {Source} source with library export
  106. */
  107. renderStartup(
  108. source,
  109. module,
  110. { moduleGraph, chunk },
  111. { options, compilation }
  112. ) {
  113. const result = new ConcatSource(source);
  114. const exportsInfos = options.export
  115. ? [
  116. moduleGraph.getExportInfo(
  117. module,
  118. Array.isArray(options.export) ? options.export[0] : options.export
  119. )
  120. ]
  121. : moduleGraph.getExportsInfo(module).orderedExports;
  122. const definitions =
  123. /** @type {BuildMeta} */
  124. (module.buildMeta).exportsFinalName || {};
  125. const shortHandedExports = [];
  126. const exports = [];
  127. const isAsync = moduleGraph.isAsync(module);
  128. if (isAsync) {
  129. result.add(
  130. `${RuntimeGlobals.exports} = await ${RuntimeGlobals.exports};\n`
  131. );
  132. }
  133. for (const exportInfo of exportsInfos) {
  134. if (!exportInfo.provided) continue;
  135. let shouldContinue = false;
  136. const reexport = exportInfo.findTarget(moduleGraph, _m => true);
  137. if (reexport) {
  138. const exp = moduleGraph.getExportsInfo(reexport.module);
  139. for (const reexportInfo of exp.orderedExports) {
  140. if (
  141. reexportInfo.provided === false &&
  142. reexportInfo.name === /** @type {string[]} */ (reexport.export)[0]
  143. ) {
  144. shouldContinue = true;
  145. }
  146. }
  147. }
  148. if (shouldContinue) continue;
  149. const webpackExportsProperty = exportInfo.getUsedName(
  150. exportInfo.name,
  151. chunk.runtime
  152. );
  153. const definition =
  154. definitions[/** @type {string} */ (webpackExportsProperty)];
  155. const finalName =
  156. definition ||
  157. `${RuntimeGlobals.exports}${Template.toIdentifier(exportInfo.name)}`;
  158. if (!definition) {
  159. result.add(
  160. `var ${finalName} = ${RuntimeGlobals.exports}${propertyAccess([
  161. /** @type {string} */
  162. (exportInfo.getUsedName(exportInfo.name, chunk.runtime))
  163. ])}\n`
  164. );
  165. }
  166. if (finalName && (finalName.includes(".") || finalName.includes("["))) {
  167. exports.push([exportInfo.name, finalName]);
  168. } else {
  169. shortHandedExports.push(
  170. definition && finalName === exportInfo.name
  171. ? finalName
  172. : `${finalName} as ${exportInfo.name}`
  173. );
  174. }
  175. }
  176. if (shortHandedExports.length > 0) {
  177. result.add(`export { ${shortHandedExports.join(", ")} };\n`);
  178. }
  179. for (const [exportName, final] of exports) {
  180. result.add(
  181. `export ${compilation.outputOptions.environment.const ? "const" : "var"} ${exportName} = ${final};\n`
  182. );
  183. }
  184. return result;
  185. }
  186. }
  187. module.exports = ModuleLibraryPlugin;