LazyCompilationPlugin.js 13 KB

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