LazyCompilationPlugin.js 14 KB

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