UNPKG

2.19 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5
6"use strict";
7
8const { find } = require("../util/SetHelpers");
9const {
10 compareModulesByPreOrderIndexOrIdentifier,
11 compareModulesByPostOrderIndexOrIdentifier
12} = require("../util/comparators");
13
14/** @typedef {import("../Compiler")} Compiler */
15
16class ChunkModuleIdRangePlugin {
17 constructor(options) {
18 this.options = options;
19 }
20
21 /**
22 * Apply the plugin
23 * @param {Compiler} compiler the compiler instance
24 * @returns {void}
25 */
26 apply(compiler) {
27 const options = this.options;
28 compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => {
29 const moduleGraph = compilation.moduleGraph;
30 compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => {
31 const chunkGraph = compilation.chunkGraph;
32 const chunk = find(
33 compilation.chunks,
34 chunk => chunk.name === options.name
35 );
36 if (!chunk) {
37 throw new Error(
38 `ChunkModuleIdRangePlugin: Chunk with name '${options.name}"' was not found`
39 );
40 }
41
42 let chunkModules;
43 if (options.order) {
44 let cmpFn;
45 switch (options.order) {
46 case "index":
47 case "preOrderIndex":
48 cmpFn = compareModulesByPreOrderIndexOrIdentifier(moduleGraph);
49 break;
50 case "index2":
51 case "postOrderIndex":
52 cmpFn = compareModulesByPostOrderIndexOrIdentifier(moduleGraph);
53 break;
54 default:
55 throw new Error(
56 "ChunkModuleIdRangePlugin: unexpected value of order"
57 );
58 }
59 chunkModules = chunkGraph.getOrderedChunkModules(chunk, cmpFn);
60 } else {
61 chunkModules = Array.from(modules)
62 .filter(m => {
63 return chunkGraph.isModuleInChunk(m, chunk);
64 })
65 .sort(compareModulesByPreOrderIndexOrIdentifier(moduleGraph));
66 }
67
68 let currentId = options.start || 0;
69 for (let i = 0; i < chunkModules.length; i++) {
70 const m = chunkModules[i];
71 if (m.needId && chunkGraph.getModuleId(m) === null) {
72 chunkGraph.setModuleId(m, currentId++);
73 }
74 if (options.end && currentId > options.end) break;
75 }
76 });
77 });
78 }
79}
80module.exports = ChunkModuleIdRangePlugin;