LazyCompilationPlugin.js 14 KB

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