webpack/lib/ids/NamedChunkIdsPlugin.js

91 lines
2.0 KiB
JavaScript
Raw Permalink Normal View History

2018-09-05 20:22:10 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { compareChunksNatural } = require("../util/comparators");
const {
2025-07-03 17:06:45 +08:00
assignAscendingChunkIds,
assignNames,
2025-07-03 17:06:45 +08:00
getLongChunkName,
getShortChunkName,
getUsedChunkIds
} = require("./IdHelpers");
2018-09-05 20:22:10 +08:00
/** @typedef {import("../Compiler")} Compiler */
2023-05-27 01:21:35 +08:00
/**
2024-06-11 21:09:50 +08:00
* @typedef {object} NamedChunkIdsPluginOptions
2025-04-16 22:04:11 +08:00
* @property {string=} context context
* @property {string=} delimiter delimiter
2023-05-27 01:21:35 +08:00
*/
2025-04-23 20:03:37 +08:00
const PLUGIN_NAME = "NamedChunkIdsPlugin";
2018-09-05 20:22:10 +08:00
class NamedChunkIdsPlugin {
2023-05-27 01:21:35 +08:00
/**
* @param {NamedChunkIdsPluginOptions=} options options
*/
constructor(options) {
this.delimiter = (options && options.delimiter) || "-";
this.context = options && options.context;
2018-09-05 20:22:10 +08:00
}
/**
2020-04-23 16:48:36 +08:00
* Apply the plugin
* @param {Compiler} compiler the compiler instance
2018-09-05 20:22:10 +08:00
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
2025-08-20 18:50:12 +08:00
const hashFunction = compilation.outputOptions.hashFunction;
compilation.hooks.chunkIds.tap(PLUGIN_NAME, (chunks) => {
2018-09-05 20:22:10 +08:00
const chunkGraph = compilation.chunkGraph;
const context = this.context ? this.context : compiler.context;
const delimiter = this.delimiter;
2018-09-05 20:22:10 +08:00
const unnamedChunks = assignNames(
[...chunks].filter((chunk) => {
if (chunk.name) {
chunk.id = chunk.name;
chunk.ids = [chunk.name];
}
return chunk.id === null;
}),
(chunk) =>
getShortChunkName(
chunk,
chunkGraph,
context,
delimiter,
hashFunction,
compiler.root
),
(chunk) =>
getLongChunkName(
chunk,
chunkGraph,
context,
delimiter,
hashFunction,
compiler.root
),
compareChunksNatural(chunkGraph),
getUsedChunkIds(compilation),
(chunk, name) => {
chunk.id = name;
chunk.ids = [name];
2018-09-05 20:22:10 +08:00
}
);
if (unnamedChunks.length > 0) {
assignAscendingChunkIds(unnamedChunks, compilation);
2018-09-05 20:22:10 +08:00
}
});
});
}
}
module.exports = NamedChunkIdsPlugin;