LazyCompilationPlugin.js 15 KB

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