webpack/lib/ids/DeterministicChunkIdsPlugin.js

73 lines
1.8 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Florent Cailhol @ooflorent
*/
"use strict";
const { compareChunksNatural } = require("../util/comparators");
const {
2025-07-03 17:06:45 +08:00
assignDeterministicIds,
getFullChunkName,
2025-07-03 17:06:45 +08:00
getUsedChunkIds
} = require("./IdHelpers");
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */
2023-05-27 01:21:35 +08:00
/**
2024-06-11 21:09:50 +08:00
* @typedef {object} DeterministicChunkIdsPluginOptions
2023-05-27 01:21:35 +08:00
* @property {string=} context context for ids
* @property {number=} maxLength maximum length of ids
*/
2025-06-04 02:20:37 +08:00
const PLUGIN_NAME = "DeterministicChunkIdsPlugin";
class DeterministicChunkIdsPlugin {
2023-05-27 01:21:35 +08:00
/**
2025-04-16 22:04:11 +08:00
* @param {DeterministicChunkIdsPluginOptions=} options options
2023-05-27 01:21:35 +08:00
*/
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) {
2025-06-04 02:20:37 +08:00
compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
compilation.hooks.chunkIds.tap(PLUGIN_NAME, chunks => {
const chunkGraph = compilation.chunkGraph;
const context = this.options.context
? this.options.context
: compiler.context;
const maxLength = this.options.maxLength || 3;
2025-06-04 02:20:37 +08:00
const compareNatural = compareChunksNatural(chunkGraph);
2025-06-04 02:20:37 +08:00
const usedIds = getUsedChunkIds(compilation);
assignDeterministicIds(
2025-07-03 17:06:45 +08:00
[...chunks].filter(chunk => chunk.id === null),
2025-06-04 02:20:37 +08:00
chunk => getFullChunkName(chunk, chunkGraph, context, compiler.root),
compareNatural,
(chunk, id) => {
const size = usedIds.size;
usedIds.add(`${id}`);
if (size === usedIds.size) return false;
chunk.id = id;
chunk.ids = [id];
return true;
},
[10 ** maxLength],
10,
usedIds.size
);
2025-06-04 02:20:37 +08:00
});
});
}
}
module.exports = DeterministicChunkIdsPlugin;