webpack/lib/ids/ChunkModuleIdRangePlugin.js

90 lines
2.4 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 23:08:51 +08:00
2017-01-11 17:51:58 +08:00
"use strict";
2018-09-06 22:59:11 +08:00
const { find } = require("../util/SetHelpers");
const {
compareModulesByPreOrderIndexOrIdentifier,
compareModulesByPostOrderIndexOrIdentifier
} = require("../util/comparators");
/** @typedef {import("../Compiler")} Compiler */
2023-05-27 01:21:35 +08:00
/**
2024-06-11 21:09:50 +08:00
* @typedef {object} ChunkModuleIdRangePluginOptions
2023-05-27 01:21:35 +08:00
* @property {string} name the chunk name
* @property {("index" | "index2" | "preOrderIndex" | "postOrderIndex")=} order order
* @property {number=} start start id
* @property {number=} end end id
*/
class ChunkModuleIdRangePlugin {
2023-05-27 01:21:35 +08:00
/**
* @param {ChunkModuleIdRangePluginOptions} options options object
*/
constructor(options) {
this.options = options;
}
/**
2020-04-23 16:48:36 +08:00
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const options = this.options;
2018-02-25 09:00:20 +08:00
compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => {
const moduleGraph = compilation.moduleGraph;
2018-02-25 09:00:20 +08:00
compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => {
const chunkGraph = compilation.chunkGraph;
2018-09-06 22:59:11 +08:00
const chunk = find(
compilation.chunks,
2018-04-04 17:26:53 +08:00
chunk => chunk.name === options.name
);
if (!chunk) {
2018-02-25 09:00:20 +08:00
throw new Error(
2019-06-09 17:23:42 +08:00
`ChunkModuleIdRangePlugin: Chunk with name '${options.name}"' was not found`
2018-02-25 09:00:20 +08:00
);
}
let chunkModules;
2018-02-25 09:00:20 +08:00
if (options.order) {
let cmpFn;
2018-02-25 09:00:20 +08:00
switch (options.order) {
case "index":
case "preOrderIndex":
cmpFn = compareModulesByPreOrderIndexOrIdentifier(moduleGraph);
break;
case "index2":
case "postOrderIndex":
cmpFn = compareModulesByPostOrderIndexOrIdentifier(moduleGraph);
break;
default:
2018-02-25 09:00:20 +08:00
throw new Error(
"ChunkModuleIdRangePlugin: unexpected value of order"
);
}
chunkModules = chunkGraph.getOrderedChunkModules(chunk, cmpFn);
} else {
2018-09-05 22:12:48 +08:00
chunkModules = Array.from(modules)
2024-07-31 11:31:11 +08:00
.filter(m => chunkGraph.isModuleInChunk(m, chunk))
.sort(compareModulesByPreOrderIndexOrIdentifier(moduleGraph));
}
let currentId = options.start || 0;
2018-02-25 09:00:20 +08:00
for (let i = 0; i < chunkModules.length; i++) {
const m = chunkModules[i];
if (m.needId && chunkGraph.getModuleId(m) === null) {
chunkGraph.setModuleId(m, currentId++);
}
2018-02-25 09:00:20 +08:00
if (options.end && currentId > options.end) break;
}
});
});
}
}
module.exports = ChunkModuleIdRangePlugin;