Compiler.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const parseJson = require("json-parse-even-better-errors");
  7. const asyncLib = require("neo-async");
  8. const {
  9. AsyncParallelHook,
  10. AsyncSeriesHook,
  11. SyncBailHook,
  12. SyncHook
  13. } = require("tapable");
  14. const { SizeOnlySource } = require("webpack-sources");
  15. const Cache = require("./Cache");
  16. const CacheFacade = require("./CacheFacade");
  17. const ChunkGraph = require("./ChunkGraph");
  18. const Compilation = require("./Compilation");
  19. const ConcurrentCompilationError = require("./ConcurrentCompilationError");
  20. const ContextModuleFactory = require("./ContextModuleFactory");
  21. const ModuleGraph = require("./ModuleGraph");
  22. const NormalModuleFactory = require("./NormalModuleFactory");
  23. const RequestShortener = require("./RequestShortener");
  24. const ResolverFactory = require("./ResolverFactory");
  25. const Stats = require("./Stats");
  26. const Watching = require("./Watching");
  27. const WebpackError = require("./WebpackError");
  28. const { Logger } = require("./logging/Logger");
  29. const { dirname, join, mkdirp } = require("./util/fs");
  30. const { makePathsRelative } = require("./util/identifier");
  31. const { isSourceEqual } = require("./util/source");
  32. const webpack = require(".");
  33. /** @typedef {import("webpack-sources").Source} Source */
  34. /** @typedef {import("../declarations/WebpackOptions").EntryNormalized} Entry */
  35. /** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */
  36. /** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */
  37. /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  38. /** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */
  39. /** @typedef {import("./Chunk")} Chunk */
  40. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  41. /** @typedef {import("./Dependency")} Dependency */
  42. /** @typedef {import("./HotModuleReplacementPlugin").ChunkHashes} ChunkHashes */
  43. /** @typedef {import("./HotModuleReplacementPlugin").ChunkModuleHashes} ChunkModuleHashes */
  44. /** @typedef {import("./HotModuleReplacementPlugin").ChunkModuleIds} ChunkModuleIds */
  45. /** @typedef {import("./HotModuleReplacementPlugin").ChunkRuntime} ChunkRuntime */
  46. /** @typedef {import("./HotModuleReplacementPlugin").FullHashChunkModuleHashes} FullHashChunkModuleHashes */
  47. /** @typedef {import("./HotModuleReplacementPlugin").HotIndex} HotIndex */
  48. /** @typedef {import("./Module")} Module */
  49. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  50. /** @typedef {import("./RecordIdsPlugin").RecordsChunks} RecordsChunks */
  51. /** @typedef {import("./RecordIdsPlugin").RecordsModules} RecordsModules */
  52. /** @typedef {import("./config/target").PlatformTargetProperties} PlatformTargetProperties */
  53. /** @typedef {import("./logging/createConsoleLogger").LoggingFunction} LoggingFunction */
  54. /** @typedef {import("./optimize/AggressiveSplittingPlugin").SplitData} SplitData */
  55. /** @typedef {import("./util/fs").IStats} IStats */
  56. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  57. /** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */
  58. /** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
  59. /** @typedef {import("./util/fs").TimeInfoEntries} TimeInfoEntries */
  60. /** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */
  61. /**
  62. * @typedef {object} CompilationParams
  63. * @property {NormalModuleFactory} normalModuleFactory
  64. * @property {ContextModuleFactory} contextModuleFactory
  65. */
  66. /**
  67. * @template T
  68. * @callback RunCallback
  69. * @param {Error | null} err
  70. * @param {T=} result
  71. */
  72. /**
  73. * @template T
  74. * @callback Callback
  75. * @param {(Error | null)=} err
  76. * @param {T=} result
  77. */
  78. /**
  79. * @callback RunAsChildCallback
  80. * @param {Error | null} err
  81. * @param {Chunk[]=} entries
  82. * @param {Compilation=} compilation
  83. */
  84. /**
  85. * @typedef {object} KnownRecords
  86. * @property {SplitData[]=} aggressiveSplits
  87. * @property {RecordsChunks=} chunks
  88. * @property {RecordsModules=} modules
  89. * @property {string=} hash
  90. * @property {HotIndex=} hotIndex
  91. * @property {FullHashChunkModuleHashes=} fullHashChunkModuleHashes
  92. * @property {ChunkModuleHashes=} chunkModuleHashes
  93. * @property {ChunkHashes=} chunkHashes
  94. * @property {ChunkRuntime=} chunkRuntime
  95. * @property {ChunkModuleIds=} chunkModuleIds
  96. */
  97. /** @typedef {KnownRecords & Record<string, KnownRecords[]> & Record<string, EXPECTED_ANY>} Records */
  98. /**
  99. * @typedef {object} AssetEmittedInfo
  100. * @property {Buffer} content
  101. * @property {Source} source
  102. * @property {Compilation} compilation
  103. * @property {string} outputPath
  104. * @property {string} targetPath
  105. */
  106. /** @typedef {{ sizeOnlySource: SizeOnlySource | undefined, writtenTo: Map<string, number> }} CacheEntry */
  107. /** @typedef {{ path: string, source: Source, size: number | undefined, waiting: ({ cacheEntry: CacheEntry, file: string }[] | undefined) }} SimilarEntry */
  108. /** @typedef {WeakMap<Dependency, Module>} WeakReferences */
  109. /** @typedef {import("./util/WeakTupleMap")<EXPECTED_ANY[], EXPECTED_ANY>} MemCache */
  110. /** @typedef {{ buildInfo: BuildInfo, references: WeakReferences | undefined, memCache: MemCache }} ModuleMemCachesItem */
  111. /**
  112. * @param {string[]} array an array
  113. * @returns {boolean} true, if the array is sorted
  114. */
  115. const isSorted = array => {
  116. for (let i = 1; i < array.length; i++) {
  117. if (array[i - 1] > array[i]) return false;
  118. }
  119. return true;
  120. };
  121. /**
  122. * @template {object} T
  123. * @param {T} obj an object
  124. * @param {(keyof T)[]} keys the keys of the object
  125. * @returns {T} the object with properties sorted by property name
  126. */
  127. const sortObject = (obj, keys) => {
  128. const o = /** @type {T} */ ({});
  129. for (const k of keys.sort()) {
  130. o[k] = obj[k];
  131. }
  132. return o;
  133. };
  134. /**
  135. * @param {string} filename filename
  136. * @param {string | string[] | undefined} hashes list of hashes
  137. * @returns {boolean} true, if the filename contains any hash
  138. */
  139. const includesHash = (filename, hashes) => {
  140. if (!hashes) return false;
  141. if (Array.isArray(hashes)) {
  142. return hashes.some(hash => filename.includes(hash));
  143. }
  144. return filename.includes(hashes);
  145. };
  146. class Compiler {
  147. /**
  148. * @param {string} context the compilation path
  149. * @param {WebpackOptions} options options
  150. */
  151. constructor(context, options = /** @type {WebpackOptions} */ ({})) {
  152. this.hooks = Object.freeze({
  153. /** @type {SyncHook<[]>} */
  154. initialize: new SyncHook([]),
  155. /** @type {SyncBailHook<[Compilation], boolean | void>} */
  156. shouldEmit: new SyncBailHook(["compilation"]),
  157. /** @type {AsyncSeriesHook<[Stats]>} */
  158. done: new AsyncSeriesHook(["stats"]),
  159. /** @type {SyncHook<[Stats]>} */
  160. afterDone: new SyncHook(["stats"]),
  161. /** @type {AsyncSeriesHook<[]>} */
  162. additionalPass: new AsyncSeriesHook([]),
  163. /** @type {AsyncSeriesHook<[Compiler]>} */
  164. beforeRun: new AsyncSeriesHook(["compiler"]),
  165. /** @type {AsyncSeriesHook<[Compiler]>} */
  166. run: new AsyncSeriesHook(["compiler"]),
  167. /** @type {AsyncSeriesHook<[Compilation]>} */
  168. emit: new AsyncSeriesHook(["compilation"]),
  169. /** @type {AsyncSeriesHook<[string, AssetEmittedInfo]>} */
  170. assetEmitted: new AsyncSeriesHook(["file", "info"]),
  171. /** @type {AsyncSeriesHook<[Compilation]>} */
  172. afterEmit: new AsyncSeriesHook(["compilation"]),
  173. /** @type {SyncHook<[Compilation, CompilationParams]>} */
  174. thisCompilation: new SyncHook(["compilation", "params"]),
  175. /** @type {SyncHook<[Compilation, CompilationParams]>} */
  176. compilation: new SyncHook(["compilation", "params"]),
  177. /** @type {SyncHook<[NormalModuleFactory]>} */
  178. normalModuleFactory: new SyncHook(["normalModuleFactory"]),
  179. /** @type {SyncHook<[ContextModuleFactory]>} */
  180. contextModuleFactory: new SyncHook(["contextModuleFactory"]),
  181. /** @type {AsyncSeriesHook<[CompilationParams]>} */
  182. beforeCompile: new AsyncSeriesHook(["params"]),
  183. /** @type {SyncHook<[CompilationParams]>} */
  184. compile: new SyncHook(["params"]),
  185. /** @type {AsyncParallelHook<[Compilation]>} */
  186. make: new AsyncParallelHook(["compilation"]),
  187. /** @type {AsyncParallelHook<[Compilation]>} */
  188. finishMake: new AsyncSeriesHook(["compilation"]),
  189. /** @type {AsyncSeriesHook<[Compilation]>} */
  190. afterCompile: new AsyncSeriesHook(["compilation"]),
  191. /** @type {AsyncSeriesHook<[]>} */
  192. readRecords: new AsyncSeriesHook([]),
  193. /** @type {AsyncSeriesHook<[]>} */
  194. emitRecords: new AsyncSeriesHook([]),
  195. /** @type {AsyncSeriesHook<[Compiler]>} */
  196. watchRun: new AsyncSeriesHook(["compiler"]),
  197. /** @type {SyncHook<[Error]>} */
  198. failed: new SyncHook(["error"]),
  199. /** @type {SyncHook<[string | null, number]>} */
  200. invalid: new SyncHook(["filename", "changeTime"]),
  201. /** @type {SyncHook<[]>} */
  202. watchClose: new SyncHook([]),
  203. /** @type {AsyncSeriesHook<[]>} */
  204. shutdown: new AsyncSeriesHook([]),
  205. /** @type {SyncBailHook<[string, string, EXPECTED_ANY[] | undefined], true | void>} */
  206. infrastructureLog: new SyncBailHook(["origin", "type", "args"]),
  207. // TODO the following hooks are weirdly located here
  208. // TODO move them for webpack 5
  209. /** @type {SyncHook<[]>} */
  210. environment: new SyncHook([]),
  211. /** @type {SyncHook<[]>} */
  212. afterEnvironment: new SyncHook([]),
  213. /** @type {SyncHook<[Compiler]>} */
  214. afterPlugins: new SyncHook(["compiler"]),
  215. /** @type {SyncHook<[Compiler]>} */
  216. afterResolvers: new SyncHook(["compiler"]),
  217. /** @type {SyncBailHook<[string, Entry], boolean | void>} */
  218. entryOption: new SyncBailHook(["context", "entry"])
  219. });
  220. this.webpack = webpack;
  221. /** @type {string | undefined} */
  222. this.name = undefined;
  223. /** @type {Compilation | undefined} */
  224. this.parentCompilation = undefined;
  225. /** @type {Compiler} */
  226. this.root = this;
  227. /** @type {string} */
  228. this.outputPath = "";
  229. /** @type {Watching | undefined} */
  230. this.watching = undefined;
  231. /** @type {OutputFileSystem | null} */
  232. this.outputFileSystem = null;
  233. /** @type {IntermediateFileSystem | null} */
  234. this.intermediateFileSystem = null;
  235. /** @type {InputFileSystem | null} */
  236. this.inputFileSystem = null;
  237. /** @type {WatchFileSystem | null} */
  238. this.watchFileSystem = null;
  239. /** @type {string | null} */
  240. this.recordsInputPath = null;
  241. /** @type {string | null} */
  242. this.recordsOutputPath = null;
  243. /** @type {Records} */
  244. this.records = {};
  245. /** @type {Set<string | RegExp>} */
  246. this.managedPaths = new Set();
  247. /** @type {Set<string | RegExp>} */
  248. this.unmanagedPaths = new Set();
  249. /** @type {Set<string | RegExp>} */
  250. this.immutablePaths = new Set();
  251. /** @type {ReadonlySet<string> | undefined} */
  252. this.modifiedFiles = undefined;
  253. /** @type {ReadonlySet<string> | undefined} */
  254. this.removedFiles = undefined;
  255. /** @type {TimeInfoEntries | undefined} */
  256. this.fileTimestamps = undefined;
  257. /** @type {TimeInfoEntries | undefined} */
  258. this.contextTimestamps = undefined;
  259. /** @type {number | undefined} */
  260. this.fsStartTime = undefined;
  261. /** @type {ResolverFactory} */
  262. this.resolverFactory = new ResolverFactory();
  263. /** @type {LoggingFunction | undefined} */
  264. this.infrastructureLogger = undefined;
  265. /** @type {Readonly<PlatformTargetProperties>} */
  266. this.platform = {
  267. web: null,
  268. browser: null,
  269. webworker: null,
  270. node: null,
  271. nwjs: null,
  272. electron: null
  273. };
  274. this.options = options;
  275. this.context = context;
  276. this.requestShortener = new RequestShortener(context, this.root);
  277. this.cache = new Cache();
  278. /** @type {Map<Module, ModuleMemCachesItem> | undefined} */
  279. this.moduleMemCaches = undefined;
  280. this.compilerPath = "";
  281. /** @type {boolean} */
  282. this.running = false;
  283. /** @type {boolean} */
  284. this.idle = false;
  285. /** @type {boolean} */
  286. this.watchMode = false;
  287. this._backCompat = this.options.experiments.backCompat !== false;
  288. /** @type {Compilation | undefined} */
  289. this._lastCompilation = undefined;
  290. /** @type {NormalModuleFactory | undefined} */
  291. this._lastNormalModuleFactory = undefined;
  292. /**
  293. * @private
  294. * @type {WeakMap<Source, CacheEntry>}
  295. */
  296. this._assetEmittingSourceCache = new WeakMap();
  297. /**
  298. * @private
  299. * @type {Map<string, number>}
  300. */
  301. this._assetEmittingWrittenFiles = new Map();
  302. /**
  303. * @private
  304. * @type {Set<string>}
  305. */
  306. this._assetEmittingPreviousFiles = new Set();
  307. }
  308. /**
  309. * @param {string} name cache name
  310. * @returns {CacheFacade} the cache facade instance
  311. */
  312. getCache(name) {
  313. return new CacheFacade(
  314. this.cache,
  315. `${this.compilerPath}${name}`,
  316. this.options.output.hashFunction
  317. );
  318. }
  319. /**
  320. * @param {string | (() => string)} name name of the logger, or function called once to get the logger name
  321. * @returns {Logger} a logger with that name
  322. */
  323. getInfrastructureLogger(name) {
  324. if (!name) {
  325. throw new TypeError(
  326. "Compiler.getInfrastructureLogger(name) called without a name"
  327. );
  328. }
  329. return new Logger(
  330. (type, args) => {
  331. if (typeof name === "function") {
  332. name = name();
  333. if (!name) {
  334. throw new TypeError(
  335. "Compiler.getInfrastructureLogger(name) called with a function not returning a name"
  336. );
  337. }
  338. }
  339. if (
  340. this.hooks.infrastructureLog.call(name, type, args) === undefined &&
  341. this.infrastructureLogger !== undefined
  342. ) {
  343. this.infrastructureLogger(name, type, args);
  344. }
  345. },
  346. childName => {
  347. if (typeof name === "function") {
  348. if (typeof childName === "function") {
  349. return this.getInfrastructureLogger(() => {
  350. if (typeof name === "function") {
  351. name = name();
  352. if (!name) {
  353. throw new TypeError(
  354. "Compiler.getInfrastructureLogger(name) called with a function not returning a name"
  355. );
  356. }
  357. }
  358. if (typeof childName === "function") {
  359. childName = childName();
  360. if (!childName) {
  361. throw new TypeError(
  362. "Logger.getChildLogger(name) called with a function not returning a name"
  363. );
  364. }
  365. }
  366. return `${name}/${childName}`;
  367. });
  368. }
  369. return this.getInfrastructureLogger(() => {
  370. if (typeof name === "function") {
  371. name = name();
  372. if (!name) {
  373. throw new TypeError(
  374. "Compiler.getInfrastructureLogger(name) called with a function not returning a name"
  375. );
  376. }
  377. }
  378. return `${name}/${childName}`;
  379. });
  380. }
  381. if (typeof childName === "function") {
  382. return this.getInfrastructureLogger(() => {
  383. if (typeof childName === "function") {
  384. childName = childName();
  385. if (!childName) {
  386. throw new TypeError(
  387. "Logger.getChildLogger(name) called with a function not returning a name"
  388. );
  389. }
  390. }
  391. return `${name}/${childName}`;
  392. });
  393. }
  394. return this.getInfrastructureLogger(`${name}/${childName}`);
  395. }
  396. );
  397. }
  398. // TODO webpack 6: solve this in a better way
  399. // e.g. move compilation specific info from Modules into ModuleGraph
  400. _cleanupLastCompilation() {
  401. if (this._lastCompilation !== undefined) {
  402. for (const childCompilation of this._lastCompilation.children) {
  403. for (const module of childCompilation.modules) {
  404. ChunkGraph.clearChunkGraphForModule(module);
  405. ModuleGraph.clearModuleGraphForModule(module);
  406. module.cleanupForCache();
  407. }
  408. for (const chunk of childCompilation.chunks) {
  409. ChunkGraph.clearChunkGraphForChunk(chunk);
  410. }
  411. }
  412. for (const module of this._lastCompilation.modules) {
  413. ChunkGraph.clearChunkGraphForModule(module);
  414. ModuleGraph.clearModuleGraphForModule(module);
  415. module.cleanupForCache();
  416. }
  417. for (const chunk of this._lastCompilation.chunks) {
  418. ChunkGraph.clearChunkGraphForChunk(chunk);
  419. }
  420. this._lastCompilation = undefined;
  421. }
  422. }
  423. // TODO webpack 6: solve this in a better way
  424. _cleanupLastNormalModuleFactory() {
  425. if (this._lastNormalModuleFactory !== undefined) {
  426. this._lastNormalModuleFactory.cleanupForCache();
  427. this._lastNormalModuleFactory = undefined;
  428. }
  429. }
  430. /**
  431. * @param {WatchOptions} watchOptions the watcher's options
  432. * @param {RunCallback<Stats>} handler signals when the call finishes
  433. * @returns {Watching} a compiler watcher
  434. */
  435. watch(watchOptions, handler) {
  436. if (this.running) {
  437. return handler(new ConcurrentCompilationError());
  438. }
  439. this.running = true;
  440. this.watchMode = true;
  441. this.watching = new Watching(this, watchOptions, handler);
  442. return this.watching;
  443. }
  444. /**
  445. * @param {RunCallback<Stats>} callback signals when the call finishes
  446. * @returns {void}
  447. */
  448. run(callback) {
  449. if (this.running) {
  450. return callback(new ConcurrentCompilationError());
  451. }
  452. /** @type {Logger | undefined} */
  453. let logger;
  454. /**
  455. * @param {Error | null} err error
  456. * @param {Stats=} stats stats
  457. */
  458. const finalCallback = (err, stats) => {
  459. if (logger) logger.time("beginIdle");
  460. this.idle = true;
  461. this.cache.beginIdle();
  462. this.idle = true;
  463. if (logger) logger.timeEnd("beginIdle");
  464. this.running = false;
  465. if (err) {
  466. this.hooks.failed.call(err);
  467. }
  468. if (callback !== undefined) callback(err, stats);
  469. this.hooks.afterDone.call(/** @type {Stats} */ (stats));
  470. };
  471. const startTime = Date.now();
  472. this.running = true;
  473. /**
  474. * @param {Error | null} err error
  475. * @param {Compilation=} _compilation compilation
  476. * @returns {void}
  477. */
  478. const onCompiled = (err, _compilation) => {
  479. if (err) return finalCallback(err);
  480. const compilation = /** @type {Compilation} */ (_compilation);
  481. if (this.hooks.shouldEmit.call(compilation) === false) {
  482. compilation.startTime = startTime;
  483. compilation.endTime = Date.now();
  484. const stats = new Stats(compilation);
  485. this.hooks.done.callAsync(stats, err => {
  486. if (err) return finalCallback(err);
  487. return finalCallback(null, stats);
  488. });
  489. return;
  490. }
  491. process.nextTick(() => {
  492. logger = compilation.getLogger("webpack.Compiler");
  493. logger.time("emitAssets");
  494. this.emitAssets(compilation, err => {
  495. /** @type {Logger} */
  496. (logger).timeEnd("emitAssets");
  497. if (err) return finalCallback(err);
  498. if (compilation.hooks.needAdditionalPass.call()) {
  499. compilation.needAdditionalPass = true;
  500. compilation.startTime = startTime;
  501. compilation.endTime = Date.now();
  502. /** @type {Logger} */
  503. (logger).time("done hook");
  504. const stats = new Stats(compilation);
  505. this.hooks.done.callAsync(stats, err => {
  506. /** @type {Logger} */
  507. (logger).timeEnd("done hook");
  508. if (err) return finalCallback(err);
  509. this.hooks.additionalPass.callAsync(err => {
  510. if (err) return finalCallback(err);
  511. this.compile(onCompiled);
  512. });
  513. });
  514. return;
  515. }
  516. /** @type {Logger} */
  517. (logger).time("emitRecords");
  518. this.emitRecords(err => {
  519. /** @type {Logger} */
  520. (logger).timeEnd("emitRecords");
  521. if (err) return finalCallback(err);
  522. compilation.startTime = startTime;
  523. compilation.endTime = Date.now();
  524. /** @type {Logger} */
  525. (logger).time("done hook");
  526. const stats = new Stats(compilation);
  527. this.hooks.done.callAsync(stats, err => {
  528. /** @type {Logger} */
  529. (logger).timeEnd("done hook");
  530. if (err) return finalCallback(err);
  531. this.cache.storeBuildDependencies(
  532. compilation.buildDependencies,
  533. err => {
  534. if (err) return finalCallback(err);
  535. return finalCallback(null, stats);
  536. }
  537. );
  538. });
  539. });
  540. });
  541. });
  542. };
  543. const run = () => {
  544. this.hooks.beforeRun.callAsync(this, err => {
  545. if (err) return finalCallback(err);
  546. this.hooks.run.callAsync(this, err => {
  547. if (err) return finalCallback(err);
  548. this.readRecords(err => {
  549. if (err) return finalCallback(err);
  550. this.compile(onCompiled);
  551. });
  552. });
  553. });
  554. };
  555. if (this.idle) {
  556. this.cache.endIdle(err => {
  557. if (err) return finalCallback(err);
  558. this.idle = false;
  559. run();
  560. });
  561. } else {
  562. run();
  563. }
  564. }
  565. /**
  566. * @param {RunAsChildCallback} callback signals when the call finishes
  567. * @returns {void}
  568. */
  569. runAsChild(callback) {
  570. const startTime = Date.now();
  571. /**
  572. * @param {Error | null} err error
  573. * @param {Chunk[]=} entries entries
  574. * @param {Compilation=} compilation compilation
  575. */
  576. const finalCallback = (err, entries, compilation) => {
  577. try {
  578. callback(err, entries, compilation);
  579. } catch (runAsChildErr) {
  580. const err = new WebpackError(
  581. `compiler.runAsChild callback error: ${runAsChildErr}`,
  582. { cause: runAsChildErr }
  583. );
  584. err.details = /** @type {Error} */ (runAsChildErr).stack;
  585. /** @type {Compilation} */
  586. (this.parentCompilation).errors.push(err);
  587. }
  588. };
  589. this.compile((err, _compilation) => {
  590. if (err) return finalCallback(err);
  591. const compilation = /** @type {Compilation} */ (_compilation);
  592. const parentCompilation = /** @type {Compilation} */ (
  593. this.parentCompilation
  594. );
  595. parentCompilation.children.push(compilation);
  596. for (const { name, source, info } of compilation.getAssets()) {
  597. parentCompilation.emitAsset(name, source, info);
  598. }
  599. /** @type {Chunk[]} */
  600. const entries = [];
  601. for (const ep of compilation.entrypoints.values()) {
  602. entries.push(...ep.chunks);
  603. }
  604. compilation.startTime = startTime;
  605. compilation.endTime = Date.now();
  606. return finalCallback(null, entries, compilation);
  607. });
  608. }
  609. purgeInputFileSystem() {
  610. if (this.inputFileSystem && this.inputFileSystem.purge) {
  611. this.inputFileSystem.purge();
  612. }
  613. }
  614. /**
  615. * @param {Compilation} compilation the compilation
  616. * @param {Callback<void>} callback signals when the assets are emitted
  617. * @returns {void}
  618. */
  619. emitAssets(compilation, callback) {
  620. /** @type {string} */
  621. let outputPath;
  622. /**
  623. * @param {Error=} err error
  624. * @returns {void}
  625. */
  626. const emitFiles = err => {
  627. if (err) return callback(err);
  628. const assets = compilation.getAssets();
  629. compilation.assets = { ...compilation.assets };
  630. /** @type {Map<string, SimilarEntry>} */
  631. const caseInsensitiveMap = new Map();
  632. /** @type {Set<string>} */
  633. const allTargetPaths = new Set();
  634. asyncLib.forEachLimit(
  635. assets,
  636. 15,
  637. ({ name: file, source, info }, callback) => {
  638. let targetFile = file;
  639. let immutable = info.immutable;
  640. const queryStringIdx = targetFile.indexOf("?");
  641. if (queryStringIdx >= 0) {
  642. targetFile = targetFile.slice(0, queryStringIdx);
  643. // We may remove the hash, which is in the query string
  644. // So we recheck if the file is immutable
  645. // This doesn't cover all cases, but immutable is only a performance optimization anyway
  646. immutable =
  647. immutable &&
  648. (includesHash(targetFile, info.contenthash) ||
  649. includesHash(targetFile, info.chunkhash) ||
  650. includesHash(targetFile, info.modulehash) ||
  651. includesHash(targetFile, info.fullhash));
  652. }
  653. /**
  654. * @param {Error=} err error
  655. * @returns {void}
  656. */
  657. const writeOut = err => {
  658. if (err) return callback(err);
  659. const targetPath = join(
  660. /** @type {OutputFileSystem} */
  661. (this.outputFileSystem),
  662. outputPath,
  663. targetFile
  664. );
  665. allTargetPaths.add(targetPath);
  666. // check if the target file has already been written by this Compiler
  667. const targetFileGeneration =
  668. this._assetEmittingWrittenFiles.get(targetPath);
  669. // create an cache entry for this Source if not already existing
  670. let cacheEntry = this._assetEmittingSourceCache.get(source);
  671. if (cacheEntry === undefined) {
  672. cacheEntry = {
  673. sizeOnlySource: undefined,
  674. writtenTo: new Map()
  675. };
  676. this._assetEmittingSourceCache.set(source, cacheEntry);
  677. }
  678. /** @type {SimilarEntry | undefined} */
  679. let similarEntry;
  680. const checkSimilarFile = () => {
  681. const caseInsensitiveTargetPath = targetPath.toLowerCase();
  682. similarEntry = caseInsensitiveMap.get(caseInsensitiveTargetPath);
  683. if (similarEntry !== undefined) {
  684. const { path: other, source: otherSource } = similarEntry;
  685. if (isSourceEqual(otherSource, source)) {
  686. // Size may or may not be available at this point.
  687. // If it's not available add to "waiting" list and it will be updated once available
  688. if (similarEntry.size !== undefined) {
  689. updateWithReplacementSource(similarEntry.size);
  690. } else {
  691. if (!similarEntry.waiting) similarEntry.waiting = [];
  692. similarEntry.waiting.push({ file, cacheEntry });
  693. }
  694. alreadyWritten();
  695. } else {
  696. const err =
  697. new WebpackError(`Prevent writing to file that only differs in casing or query string from already written file.
  698. This will lead to a race-condition and corrupted files on case-insensitive file systems.
  699. ${targetPath}
  700. ${other}`);
  701. err.file = file;
  702. callback(err);
  703. }
  704. return true;
  705. }
  706. caseInsensitiveMap.set(
  707. caseInsensitiveTargetPath,
  708. (similarEntry = /** @type {SimilarEntry} */ ({
  709. path: targetPath,
  710. source,
  711. size: undefined,
  712. waiting: undefined
  713. }))
  714. );
  715. return false;
  716. };
  717. /**
  718. * get the binary (Buffer) content from the Source
  719. * @returns {Buffer} content for the source
  720. */
  721. const getContent = () => {
  722. if (typeof source.buffer === "function") {
  723. return source.buffer();
  724. }
  725. const bufferOrString = source.source();
  726. if (Buffer.isBuffer(bufferOrString)) {
  727. return bufferOrString;
  728. }
  729. return Buffer.from(bufferOrString, "utf8");
  730. };
  731. const alreadyWritten = () => {
  732. // cache the information that the Source has been already been written to that location
  733. if (targetFileGeneration === undefined) {
  734. const newGeneration = 1;
  735. this._assetEmittingWrittenFiles.set(targetPath, newGeneration);
  736. /** @type {CacheEntry} */
  737. (cacheEntry).writtenTo.set(targetPath, newGeneration);
  738. } else {
  739. /** @type {CacheEntry} */
  740. (cacheEntry).writtenTo.set(targetPath, targetFileGeneration);
  741. }
  742. callback();
  743. };
  744. /**
  745. * Write the file to output file system
  746. * @param {Buffer} content content to be written
  747. * @returns {void}
  748. */
  749. const doWrite = content => {
  750. /** @type {OutputFileSystem} */
  751. (this.outputFileSystem).writeFile(targetPath, content, err => {
  752. if (err) return callback(err);
  753. // information marker that the asset has been emitted
  754. compilation.emittedAssets.add(file);
  755. // cache the information that the Source has been written to that location
  756. const newGeneration =
  757. targetFileGeneration === undefined
  758. ? 1
  759. : targetFileGeneration + 1;
  760. /** @type {CacheEntry} */
  761. (cacheEntry).writtenTo.set(targetPath, newGeneration);
  762. this._assetEmittingWrittenFiles.set(targetPath, newGeneration);
  763. this.hooks.assetEmitted.callAsync(
  764. file,
  765. {
  766. content,
  767. source,
  768. outputPath,
  769. compilation,
  770. targetPath
  771. },
  772. callback
  773. );
  774. });
  775. };
  776. /**
  777. * @param {number} size size
  778. */
  779. const updateWithReplacementSource = size => {
  780. updateFileWithReplacementSource(
  781. file,
  782. /** @type {CacheEntry} */ (cacheEntry),
  783. size
  784. );
  785. /** @type {SimilarEntry} */
  786. (similarEntry).size = size;
  787. if (
  788. /** @type {SimilarEntry} */ (similarEntry).waiting !== undefined
  789. ) {
  790. for (const { file, cacheEntry } of /** @type {SimilarEntry} */ (
  791. similarEntry
  792. ).waiting) {
  793. updateFileWithReplacementSource(file, cacheEntry, size);
  794. }
  795. }
  796. };
  797. /**
  798. * @param {string} file file
  799. * @param {CacheEntry} cacheEntry cache entry
  800. * @param {number} size size
  801. */
  802. const updateFileWithReplacementSource = (
  803. file,
  804. cacheEntry,
  805. size
  806. ) => {
  807. // Create a replacement resource which only allows to ask for size
  808. // This allows to GC all memory allocated by the Source
  809. // (expect when the Source is stored in any other cache)
  810. if (!cacheEntry.sizeOnlySource) {
  811. cacheEntry.sizeOnlySource = new SizeOnlySource(size);
  812. }
  813. compilation.updateAsset(file, cacheEntry.sizeOnlySource, {
  814. size
  815. });
  816. };
  817. /**
  818. * @param {IStats} stats stats
  819. * @returns {void}
  820. */
  821. const processExistingFile = stats => {
  822. // skip emitting if it's already there and an immutable file
  823. if (immutable) {
  824. updateWithReplacementSource(/** @type {number} */ (stats.size));
  825. return alreadyWritten();
  826. }
  827. const content = getContent();
  828. updateWithReplacementSource(content.length);
  829. // if it exists and content on disk matches content
  830. // skip writing the same content again
  831. // (to keep mtime and don't trigger watchers)
  832. // for a fast negative match file size is compared first
  833. if (content.length === stats.size) {
  834. compilation.comparedForEmitAssets.add(file);
  835. return /** @type {OutputFileSystem} */ (
  836. this.outputFileSystem
  837. ).readFile(targetPath, (err, existingContent) => {
  838. if (
  839. err ||
  840. !content.equals(/** @type {Buffer} */ (existingContent))
  841. ) {
  842. return doWrite(content);
  843. }
  844. return alreadyWritten();
  845. });
  846. }
  847. return doWrite(content);
  848. };
  849. const processMissingFile = () => {
  850. const content = getContent();
  851. updateWithReplacementSource(content.length);
  852. return doWrite(content);
  853. };
  854. // if the target file has already been written
  855. if (targetFileGeneration !== undefined) {
  856. // check if the Source has been written to this target file
  857. const writtenGeneration = /** @type {CacheEntry} */ (
  858. cacheEntry
  859. ).writtenTo.get(targetPath);
  860. if (writtenGeneration === targetFileGeneration) {
  861. // if yes, we may skip writing the file
  862. // if it's already there
  863. // (we assume one doesn't modify files while the Compiler is running, other then removing them)
  864. if (this._assetEmittingPreviousFiles.has(targetPath)) {
  865. const sizeOnlySource = /** @type {SizeOnlySource} */ (
  866. /** @type {CacheEntry} */ (cacheEntry).sizeOnlySource
  867. );
  868. // We assume that assets from the last compilation say intact on disk (they are not removed)
  869. compilation.updateAsset(file, sizeOnlySource, {
  870. size: sizeOnlySource.size()
  871. });
  872. return callback();
  873. }
  874. // Settings immutable will make it accept file content without comparing when file exist
  875. immutable = true;
  876. } else if (!immutable) {
  877. if (checkSimilarFile()) return;
  878. // We wrote to this file before which has very likely a different content
  879. // skip comparing and assume content is different for performance
  880. // This case happens often during watch mode.
  881. return processMissingFile();
  882. }
  883. }
  884. if (checkSimilarFile()) return;
  885. if (this.options.output.compareBeforeEmit) {
  886. /** @type {OutputFileSystem} */
  887. (this.outputFileSystem).stat(targetPath, (err, stats) => {
  888. const exists = !err && /** @type {IStats} */ (stats).isFile();
  889. if (exists) {
  890. processExistingFile(/** @type {IStats} */ (stats));
  891. } else {
  892. processMissingFile();
  893. }
  894. });
  895. } else {
  896. processMissingFile();
  897. }
  898. };
  899. if (/\/|\\/.test(targetFile)) {
  900. const fs = /** @type {OutputFileSystem} */ (this.outputFileSystem);
  901. const dir = dirname(fs, join(fs, outputPath, targetFile));
  902. mkdirp(fs, dir, writeOut);
  903. } else {
  904. writeOut();
  905. }
  906. },
  907. err => {
  908. // Clear map to free up memory
  909. caseInsensitiveMap.clear();
  910. if (err) {
  911. this._assetEmittingPreviousFiles.clear();
  912. return callback(err);
  913. }
  914. this._assetEmittingPreviousFiles = allTargetPaths;
  915. this.hooks.afterEmit.callAsync(compilation, err => {
  916. if (err) return callback(err);
  917. return callback();
  918. });
  919. }
  920. );
  921. };
  922. this.hooks.emit.callAsync(compilation, err => {
  923. if (err) return callback(err);
  924. outputPath = compilation.getPath(this.outputPath, {});
  925. mkdirp(
  926. /** @type {OutputFileSystem} */ (this.outputFileSystem),
  927. outputPath,
  928. emitFiles
  929. );
  930. });
  931. }
  932. /**
  933. * @param {Callback<void>} callback signals when the call finishes
  934. * @returns {void}
  935. */
  936. emitRecords(callback) {
  937. if (this.hooks.emitRecords.isUsed()) {
  938. if (this.recordsOutputPath) {
  939. asyncLib.parallel(
  940. [
  941. cb => this.hooks.emitRecords.callAsync(cb),
  942. this._emitRecords.bind(this)
  943. ],
  944. err => callback(err)
  945. );
  946. } else {
  947. this.hooks.emitRecords.callAsync(callback);
  948. }
  949. } else if (this.recordsOutputPath) {
  950. this._emitRecords(callback);
  951. } else {
  952. callback();
  953. }
  954. }
  955. /**
  956. * @param {Callback<void>} callback signals when the call finishes
  957. * @returns {void}
  958. */
  959. _emitRecords(callback) {
  960. const writeFile = () => {
  961. /** @type {OutputFileSystem} */
  962. (this.outputFileSystem).writeFile(
  963. /** @type {string} */ (this.recordsOutputPath),
  964. JSON.stringify(
  965. this.records,
  966. (n, value) => {
  967. if (
  968. typeof value === "object" &&
  969. value !== null &&
  970. !Array.isArray(value)
  971. ) {
  972. const keys = Object.keys(value);
  973. if (!isSorted(keys)) {
  974. return sortObject(value, keys);
  975. }
  976. }
  977. return value;
  978. },
  979. 2
  980. ),
  981. callback
  982. );
  983. };
  984. const recordsOutputPathDirectory = dirname(
  985. /** @type {OutputFileSystem} */
  986. (this.outputFileSystem),
  987. /** @type {string} */
  988. (this.recordsOutputPath)
  989. );
  990. if (!recordsOutputPathDirectory) {
  991. return writeFile();
  992. }
  993. mkdirp(
  994. /** @type {OutputFileSystem} */ (this.outputFileSystem),
  995. recordsOutputPathDirectory,
  996. err => {
  997. if (err) return callback(err);
  998. writeFile();
  999. }
  1000. );
  1001. }
  1002. /**
  1003. * @param {Callback<void>} callback signals when the call finishes
  1004. * @returns {void}
  1005. */
  1006. readRecords(callback) {
  1007. if (this.hooks.readRecords.isUsed()) {
  1008. if (this.recordsInputPath) {
  1009. asyncLib.parallel(
  1010. [
  1011. cb => this.hooks.readRecords.callAsync(cb),
  1012. this._readRecords.bind(this)
  1013. ],
  1014. err => callback(err)
  1015. );
  1016. } else {
  1017. this.records = {};
  1018. this.hooks.readRecords.callAsync(callback);
  1019. }
  1020. } else if (this.recordsInputPath) {
  1021. this._readRecords(callback);
  1022. } else {
  1023. this.records = {};
  1024. callback();
  1025. }
  1026. }
  1027. /**
  1028. * @param {Callback<void>} callback signals when the call finishes
  1029. * @returns {void}
  1030. */
  1031. _readRecords(callback) {
  1032. if (!this.recordsInputPath) {
  1033. this.records = {};
  1034. return callback();
  1035. }
  1036. /** @type {InputFileSystem} */
  1037. (this.inputFileSystem).stat(this.recordsInputPath, err => {
  1038. // It doesn't exist
  1039. // We can ignore this.
  1040. if (err) return callback();
  1041. /** @type {InputFileSystem} */
  1042. (this.inputFileSystem).readFile(
  1043. /** @type {string} */ (this.recordsInputPath),
  1044. (err, content) => {
  1045. if (err) return callback(err);
  1046. try {
  1047. this.records = parseJson(
  1048. /** @type {Buffer} */ (content).toString("utf8")
  1049. );
  1050. } catch (parseErr) {
  1051. return callback(
  1052. new Error(
  1053. `Cannot parse records: ${/** @type {Error} */ (parseErr).message}`
  1054. )
  1055. );
  1056. }
  1057. return callback();
  1058. }
  1059. );
  1060. });
  1061. }
  1062. /**
  1063. * @param {Compilation} compilation the compilation
  1064. * @param {string} compilerName the compiler's name
  1065. * @param {number} compilerIndex the compiler's index
  1066. * @param {Partial<OutputOptions>=} outputOptions the output options
  1067. * @param {WebpackPluginInstance[]=} plugins the plugins to apply
  1068. * @returns {Compiler} a child compiler
  1069. */
  1070. createChildCompiler(
  1071. compilation,
  1072. compilerName,
  1073. compilerIndex,
  1074. outputOptions,
  1075. plugins
  1076. ) {
  1077. const childCompiler = new Compiler(this.context, {
  1078. ...this.options,
  1079. output: {
  1080. ...this.options.output,
  1081. ...outputOptions
  1082. }
  1083. });
  1084. childCompiler.name = compilerName;
  1085. childCompiler.outputPath = this.outputPath;
  1086. childCompiler.inputFileSystem = this.inputFileSystem;
  1087. childCompiler.outputFileSystem = null;
  1088. childCompiler.resolverFactory = this.resolverFactory;
  1089. childCompiler.modifiedFiles = this.modifiedFiles;
  1090. childCompiler.removedFiles = this.removedFiles;
  1091. childCompiler.fileTimestamps = this.fileTimestamps;
  1092. childCompiler.contextTimestamps = this.contextTimestamps;
  1093. childCompiler.fsStartTime = this.fsStartTime;
  1094. childCompiler.cache = this.cache;
  1095. childCompiler.compilerPath = `${this.compilerPath}${compilerName}|${compilerIndex}|`;
  1096. childCompiler._backCompat = this._backCompat;
  1097. const relativeCompilerName = makePathsRelative(
  1098. this.context,
  1099. compilerName,
  1100. this.root
  1101. );
  1102. if (!this.records[relativeCompilerName]) {
  1103. this.records[relativeCompilerName] = [];
  1104. }
  1105. if (this.records[relativeCompilerName][compilerIndex]) {
  1106. childCompiler.records =
  1107. /** @type {Records} */
  1108. (this.records[relativeCompilerName][compilerIndex]);
  1109. } else {
  1110. this.records[relativeCompilerName].push((childCompiler.records = {}));
  1111. }
  1112. childCompiler.parentCompilation = compilation;
  1113. childCompiler.root = this.root;
  1114. if (Array.isArray(plugins)) {
  1115. for (const plugin of plugins) {
  1116. if (plugin) {
  1117. plugin.apply(childCompiler);
  1118. }
  1119. }
  1120. }
  1121. for (const name in this.hooks) {
  1122. if (
  1123. ![
  1124. "make",
  1125. "compile",
  1126. "emit",
  1127. "afterEmit",
  1128. "invalid",
  1129. "done",
  1130. "thisCompilation"
  1131. ].includes(name) &&
  1132. childCompiler.hooks[/** @type {keyof Compiler["hooks"]} */ (name)]
  1133. ) {
  1134. childCompiler.hooks[
  1135. /** @type {keyof Compiler["hooks"]} */
  1136. (name)
  1137. ].taps = [
  1138. ...this.hooks[
  1139. /** @type {keyof Compiler["hooks"]} */
  1140. (name)
  1141. ].taps
  1142. ];
  1143. }
  1144. }
  1145. compilation.hooks.childCompiler.call(
  1146. childCompiler,
  1147. compilerName,
  1148. compilerIndex
  1149. );
  1150. return childCompiler;
  1151. }
  1152. isChild() {
  1153. return Boolean(this.parentCompilation);
  1154. }
  1155. /**
  1156. * @param {CompilationParams} params the compilation parameters
  1157. * @returns {Compilation} compilation
  1158. */
  1159. createCompilation(params) {
  1160. this._cleanupLastCompilation();
  1161. return (this._lastCompilation = new Compilation(this, params));
  1162. }
  1163. /**
  1164. * @param {CompilationParams} params the compilation parameters
  1165. * @returns {Compilation} the created compilation
  1166. */
  1167. newCompilation(params) {
  1168. const compilation = this.createCompilation(params);
  1169. compilation.name = this.name;
  1170. compilation.records = this.records;
  1171. this.hooks.thisCompilation.call(compilation, params);
  1172. this.hooks.compilation.call(compilation, params);
  1173. return compilation;
  1174. }
  1175. createNormalModuleFactory() {
  1176. this._cleanupLastNormalModuleFactory();
  1177. const normalModuleFactory = new NormalModuleFactory({
  1178. context: this.options.context,
  1179. fs: /** @type {InputFileSystem} */ (this.inputFileSystem),
  1180. resolverFactory: this.resolverFactory,
  1181. options: this.options.module,
  1182. associatedObjectForCache: this.root,
  1183. layers: this.options.experiments.layers
  1184. });
  1185. this._lastNormalModuleFactory = normalModuleFactory;
  1186. this.hooks.normalModuleFactory.call(normalModuleFactory);
  1187. return normalModuleFactory;
  1188. }
  1189. createContextModuleFactory() {
  1190. const contextModuleFactory = new ContextModuleFactory(this.resolverFactory);
  1191. this.hooks.contextModuleFactory.call(contextModuleFactory);
  1192. return contextModuleFactory;
  1193. }
  1194. newCompilationParams() {
  1195. const params = {
  1196. normalModuleFactory: this.createNormalModuleFactory(),
  1197. contextModuleFactory: this.createContextModuleFactory()
  1198. };
  1199. return params;
  1200. }
  1201. /**
  1202. * @param {RunCallback<Compilation>} callback signals when the compilation finishes
  1203. * @returns {void}
  1204. */
  1205. compile(callback) {
  1206. const params = this.newCompilationParams();
  1207. this.hooks.beforeCompile.callAsync(params, err => {
  1208. if (err) return callback(err);
  1209. this.hooks.compile.call(params);
  1210. const compilation = this.newCompilation(params);
  1211. const logger = compilation.getLogger("webpack.Compiler");
  1212. logger.time("make hook");
  1213. this.hooks.make.callAsync(compilation, err => {
  1214. logger.timeEnd("make hook");
  1215. if (err) return callback(err);
  1216. logger.time("finish make hook");
  1217. this.hooks.finishMake.callAsync(compilation, err => {
  1218. logger.timeEnd("finish make hook");
  1219. if (err) return callback(err);
  1220. process.nextTick(() => {
  1221. logger.time("finish compilation");
  1222. compilation.finish(err => {
  1223. logger.timeEnd("finish compilation");
  1224. if (err) return callback(err);
  1225. logger.time("seal compilation");
  1226. compilation.seal(err => {
  1227. logger.timeEnd("seal compilation");
  1228. if (err) return callback(err);
  1229. logger.time("afterCompile hook");
  1230. this.hooks.afterCompile.callAsync(compilation, err => {
  1231. logger.timeEnd("afterCompile hook");
  1232. if (err) return callback(err);
  1233. return callback(null, compilation);
  1234. });
  1235. });
  1236. });
  1237. });
  1238. });
  1239. });
  1240. });
  1241. }
  1242. /**
  1243. * @param {RunCallback<void>} callback signals when the compiler closes
  1244. * @returns {void}
  1245. */
  1246. close(callback) {
  1247. if (this.watching) {
  1248. // When there is still an active watching, close this first
  1249. this.watching.close(_err => {
  1250. this.close(callback);
  1251. });
  1252. return;
  1253. }
  1254. this.hooks.shutdown.callAsync(err => {
  1255. if (err) return callback(err);
  1256. // Get rid of reference to last compilation to avoid leaking memory
  1257. // We can't run this._cleanupLastCompilation() as the Stats to this compilation
  1258. // might be still in use. We try to get rid of the reference to the cache instead.
  1259. this._lastCompilation = undefined;
  1260. this._lastNormalModuleFactory = undefined;
  1261. this.cache.shutdown(callback);
  1262. });
  1263. }
  1264. }
  1265. module.exports = Compiler;