LazyCompilationPlugin.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { RawSource } = require("webpack-sources");
  7. const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
  8. const Dependency = require("../Dependency");
  9. const Module = require("../Module");
  10. const ModuleFactory = require("../ModuleFactory");
  11. const {
  12. WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY
  13. } = require("../ModuleTypeConstants");
  14. const RuntimeGlobals = require("../RuntimeGlobals");
  15. const Template = require("../Template");
  16. const CommonJsRequireDependency = require("../dependencies/CommonJsRequireDependency");
  17. const { registerNotSerializable } = require("../util/serialization");
  18. /** @typedef {import("../../declarations/WebpackOptions")} WebpackOptions */
  19. /** @typedef {import("../Compilation")} Compilation */
  20. /** @typedef {import("../Compiler")} Compiler */
  21. /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
  22. /** @typedef {import("../Module").BuildMeta} BuildMeta */
  23. /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
  24. /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
  25. /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
  26. /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
  27. /** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
  28. /** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
  29. /** @typedef {import("../RequestShortener")} RequestShortener */
  30. /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  31. /** @typedef {import("../WebpackError")} WebpackError */
  32. /** @typedef {import("../dependencies/HarmonyImportDependency")} HarmonyImportDependency */
  33. /** @typedef {import("../util/Hash")} Hash */
  34. /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
  35. /**
  36. * @typedef {Object} BackendApi
  37. * @property {function(Error=): void} dispose
  38. * @property {function(Module): { client: string, data: string, active: boolean }} module
  39. */
  40. const HMR_DEPENDENCY_TYPES = new Set([
  41. "import.meta.webpackHot.accept",
  42. "import.meta.webpackHot.decline",
  43. "module.hot.accept",
  44. "module.hot.decline"
  45. ]);
  46. /**
  47. * @param {undefined|string|RegExp|Function} test test option
  48. * @param {Module} module the module
  49. * @returns {boolean} true, if the module should be selected
  50. */
  51. const checkTest = (test, module) => {
  52. if (test === undefined) return true;
  53. if (typeof test === "function") {
  54. return test(module);
  55. }
  56. if (typeof test === "string") {
  57. const name = module.nameForCondition();
  58. return name && name.startsWith(test);
  59. }
  60. if (test instanceof RegExp) {
  61. const name = module.nameForCondition();
  62. return name && test.test(name);
  63. }
  64. return false;
  65. };
  66. const TYPES = new Set(["javascript"]);
  67. class LazyCompilationDependency extends Dependency {
  68. constructor(proxyModule) {
  69. super();
  70. this.proxyModule = proxyModule;
  71. }
  72. get category() {
  73. return "esm";
  74. }
  75. get type() {
  76. return "lazy import()";
  77. }
  78. /**
  79. * @returns {string | null} an identifier to merge equal requests
  80. */
  81. getResourceIdentifier() {
  82. return this.proxyModule.originalModule.identifier();
  83. }
  84. }
  85. registerNotSerializable(LazyCompilationDependency);
  86. class LazyCompilationProxyModule extends Module {
  87. constructor(context, originalModule, request, client, data, active) {
  88. super(
  89. WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY,
  90. context,
  91. originalModule.layer
  92. );
  93. this.originalModule = originalModule;
  94. this.request = request;
  95. this.client = client;
  96. this.data = data;
  97. this.active = active;
  98. }
  99. /**
  100. * @returns {string} a unique identifier of the module
  101. */
  102. identifier() {
  103. return `${WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY}|${this.originalModule.identifier()}`;
  104. }
  105. /**
  106. * @param {RequestShortener} requestShortener the request shortener
  107. * @returns {string} a user readable identifier of the module
  108. */
  109. readableIdentifier(requestShortener) {
  110. return `${WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY} ${this.originalModule.readableIdentifier(
  111. requestShortener
  112. )}`;
  113. }
  114. /**
  115. * Assuming this module is in the cache. Update the (cached) module with
  116. * the fresh module from the factory. Usually updates internal references
  117. * and properties.
  118. * @param {Module} module fresh module
  119. * @returns {void}
  120. */
  121. updateCacheModule(module) {
  122. super.updateCacheModule(module);
  123. const m = /** @type {LazyCompilationProxyModule} */ (module);
  124. this.originalModule = m.originalModule;
  125. this.request = m.request;
  126. this.client = m.client;
  127. this.data = m.data;
  128. this.active = m.active;
  129. }
  130. /**
  131. * @param {LibIdentOptions} options options
  132. * @returns {string | null} an identifier for library inclusion
  133. */
  134. libIdent(options) {
  135. return `${this.originalModule.libIdent(
  136. options
  137. )}!${WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY}`;
  138. }
  139. /**
  140. * @param {NeedBuildContext} context context info
  141. * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
  142. * @returns {void}
  143. */
  144. needBuild(context, callback) {
  145. callback(null, !this.buildInfo || this.buildInfo.active !== this.active);
  146. }
  147. /**
  148. * @param {WebpackOptions} options webpack options
  149. * @param {Compilation} compilation the compilation
  150. * @param {ResolverWithOptions} resolver the resolver
  151. * @param {InputFileSystem} fs the file system
  152. * @param {function(WebpackError=): void} callback callback function
  153. * @returns {void}
  154. */
  155. build(options, compilation, resolver, fs, callback) {
  156. this.buildInfo = {
  157. active: this.active
  158. };
  159. /** @type {BuildMeta} */
  160. this.buildMeta = {};
  161. this.clearDependenciesAndBlocks();
  162. const dep = new CommonJsRequireDependency(this.client);
  163. this.addDependency(dep);
  164. if (this.active) {
  165. const dep = new LazyCompilationDependency(this);
  166. const block = new AsyncDependenciesBlock({});
  167. block.addDependency(dep);
  168. this.addBlock(block);
  169. }
  170. callback();
  171. }
  172. /**
  173. * @returns {Set<string>} types available (do not mutate)
  174. */
  175. getSourceTypes() {
  176. return TYPES;
  177. }
  178. /**
  179. * @param {string=} type the source type for which the size should be estimated
  180. * @returns {number} the estimated size of the module (must be non-zero)
  181. */
  182. size(type) {
  183. return 200;
  184. }
  185. /**
  186. * @param {CodeGenerationContext} context context for code generation
  187. * @returns {CodeGenerationResult} result
  188. */
  189. codeGeneration({ runtimeTemplate, chunkGraph, moduleGraph }) {
  190. const sources = new Map();
  191. const runtimeRequirements = new Set();
  192. runtimeRequirements.add(RuntimeGlobals.module);
  193. const clientDep = /** @type {CommonJsRequireDependency} */ (
  194. this.dependencies[0]
  195. );
  196. const clientModule = moduleGraph.getModule(clientDep);
  197. const block = this.blocks[0];
  198. const client = Template.asString([
  199. `var client = ${runtimeTemplate.moduleExports({
  200. module: clientModule,
  201. chunkGraph,
  202. request: clientDep.userRequest,
  203. runtimeRequirements
  204. })}`,
  205. `var data = ${JSON.stringify(this.data)};`
  206. ]);
  207. const keepActive = Template.asString([
  208. `var dispose = client.keepAlive({ data: data, active: ${JSON.stringify(
  209. !!block
  210. )}, module: module, onError: onError });`
  211. ]);
  212. let source;
  213. if (block) {
  214. const dep = block.dependencies[0];
  215. const module = moduleGraph.getModule(dep);
  216. source = Template.asString([
  217. client,
  218. `module.exports = ${runtimeTemplate.moduleNamespacePromise({
  219. chunkGraph,
  220. block,
  221. module,
  222. request: this.request,
  223. strict: false, // TODO this should be inherited from the original module
  224. message: "import()",
  225. runtimeRequirements
  226. })};`,
  227. "if (module.hot) {",
  228. Template.indent([
  229. "module.hot.accept();",
  230. `module.hot.accept(${JSON.stringify(
  231. chunkGraph.getModuleId(module)
  232. )}, function() { module.hot.invalidate(); });`,
  233. "module.hot.dispose(function(data) { delete data.resolveSelf; dispose(data); });",
  234. "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);"
  235. ]),
  236. "}",
  237. "function onError() { /* ignore */ }",
  238. keepActive
  239. ]);
  240. } else {
  241. source = Template.asString([
  242. client,
  243. "var resolveSelf, onError;",
  244. `module.exports = new Promise(function(resolve, reject) { resolveSelf = resolve; onError = reject; });`,
  245. "if (module.hot) {",
  246. Template.indent([
  247. "module.hot.accept();",
  248. "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);",
  249. "module.hot.dispose(function(data) { data.resolveSelf = resolveSelf; dispose(data); });"
  250. ]),
  251. "}",
  252. keepActive
  253. ]);
  254. }
  255. sources.set("javascript", new RawSource(source));
  256. return {
  257. sources,
  258. runtimeRequirements
  259. };
  260. }
  261. /**
  262. * @param {Hash} hash the hash used to track dependencies
  263. * @param {UpdateHashContext} context context
  264. * @returns {void}
  265. */
  266. updateHash(hash, context) {
  267. super.updateHash(hash, context);
  268. hash.update(this.active ? "active" : "");
  269. hash.update(JSON.stringify(this.data));
  270. }
  271. }
  272. registerNotSerializable(LazyCompilationProxyModule);
  273. class LazyCompilationDependencyFactory extends ModuleFactory {
  274. constructor(factory) {
  275. super();
  276. this._factory = factory;
  277. }
  278. /**
  279. * @param {ModuleFactoryCreateData} data data object
  280. * @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback
  281. * @returns {void}
  282. */
  283. create(data, callback) {
  284. const dependency = /** @type {LazyCompilationDependency} */ (
  285. data.dependencies[0]
  286. );
  287. callback(null, {
  288. module: dependency.proxyModule.originalModule
  289. });
  290. }
  291. }
  292. class LazyCompilationPlugin {
  293. /**
  294. * @param {Object} options options
  295. * @param {(function(Compiler, function(Error?, BackendApi?): void): void) | function(Compiler): Promise<BackendApi>} options.backend the backend
  296. * @param {boolean} options.entries true, when entries are lazy compiled
  297. * @param {boolean} options.imports true, when import() modules are lazy compiled
  298. * @param {RegExp | string | (function(Module): boolean)} options.test additional filter for lazy compiled entrypoint modules
  299. */
  300. constructor({ backend, entries, imports, test }) {
  301. this.backend = backend;
  302. this.entries = entries;
  303. this.imports = imports;
  304. this.test = test;
  305. }
  306. /**
  307. * Apply the plugin
  308. * @param {Compiler} compiler the compiler instance
  309. * @returns {void}
  310. */
  311. apply(compiler) {
  312. let backend;
  313. compiler.hooks.beforeCompile.tapAsync(
  314. "LazyCompilationPlugin",
  315. (params, callback) => {
  316. if (backend !== undefined) return callback();
  317. const promise = this.backend(compiler, (err, result) => {
  318. if (err) return callback(err);
  319. backend = result;
  320. callback();
  321. });
  322. if (promise && promise.then) {
  323. promise.then(b => {
  324. backend = b;
  325. callback();
  326. }, callback);
  327. }
  328. }
  329. );
  330. compiler.hooks.thisCompilation.tap(
  331. "LazyCompilationPlugin",
  332. (compilation, { normalModuleFactory }) => {
  333. normalModuleFactory.hooks.module.tap(
  334. "LazyCompilationPlugin",
  335. (originalModule, createData, resolveData) => {
  336. if (
  337. resolveData.dependencies.every(dep =>
  338. HMR_DEPENDENCY_TYPES.has(dep.type)
  339. )
  340. ) {
  341. // for HMR only resolving, try to determine if the HMR accept/decline refers to
  342. // an import() or not
  343. const hmrDep = resolveData.dependencies[0];
  344. const originModule =
  345. compilation.moduleGraph.getParentModule(hmrDep);
  346. const isReferringToDynamicImport = originModule.blocks.some(
  347. block =>
  348. block.dependencies.some(
  349. dep =>
  350. dep.type === "import()" &&
  351. /** @type {HarmonyImportDependency} */ (dep).request ===
  352. hmrDep.request
  353. )
  354. );
  355. if (!isReferringToDynamicImport) return;
  356. } else if (
  357. !resolveData.dependencies.every(
  358. dep =>
  359. HMR_DEPENDENCY_TYPES.has(dep.type) ||
  360. (this.imports &&
  361. (dep.type === "import()" ||
  362. dep.type === "import() context element")) ||
  363. (this.entries && dep.type === "entry")
  364. )
  365. )
  366. return;
  367. if (
  368. /webpack[/\\]hot[/\\]|webpack-dev-server[/\\]client|webpack-hot-middleware[/\\]client/.test(
  369. resolveData.request
  370. ) ||
  371. !checkTest(this.test, originalModule)
  372. )
  373. return;
  374. const moduleInfo = backend.module(originalModule);
  375. if (!moduleInfo) return;
  376. const { client, data, active } = moduleInfo;
  377. return new LazyCompilationProxyModule(
  378. compiler.context,
  379. originalModule,
  380. resolveData.request,
  381. client,
  382. data,
  383. active
  384. );
  385. }
  386. );
  387. compilation.dependencyFactories.set(
  388. LazyCompilationDependency,
  389. new LazyCompilationDependencyFactory()
  390. );
  391. }
  392. );
  393. compiler.hooks.shutdown.tapAsync("LazyCompilationPlugin", callback => {
  394. backend.dispose(callback);
  395. });
  396. }
  397. }
  398. module.exports = LazyCompilationPlugin;