LazyCompilationPlugin.js 13 KB

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