LazyCompilationPlugin.js 12 KB

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