| 1 | /*
|
|---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
|---|
| 3 | Author Florent Cailhol @ooflorent
|
|---|
| 4 | */
|
|---|
| 5 |
|
|---|
| 6 | "use strict";
|
|---|
| 7 |
|
|---|
| 8 | const { compareChunksNatural } = require("../util/comparators");
|
|---|
| 9 | const {
|
|---|
| 10 | assignDeterministicIds,
|
|---|
| 11 | getFullChunkName,
|
|---|
| 12 | getUsedChunkIds
|
|---|
| 13 | } = require("./IdHelpers");
|
|---|
| 14 |
|
|---|
| 15 | /** @typedef {import("../Compiler")} Compiler */
|
|---|
| 16 |
|
|---|
| 17 | /**
|
|---|
| 18 | * Defines the deterministic chunk ids plugin options type used by this module.
|
|---|
| 19 | * @typedef {object} DeterministicChunkIdsPluginOptions
|
|---|
| 20 | * @property {string=} context context for ids
|
|---|
| 21 | * @property {number=} maxLength maximum length of ids
|
|---|
| 22 | */
|
|---|
| 23 |
|
|---|
| 24 | const PLUGIN_NAME = "DeterministicChunkIdsPlugin";
|
|---|
| 25 |
|
|---|
| 26 | class DeterministicChunkIdsPlugin {
|
|---|
| 27 | /**
|
|---|
| 28 | * Creates an instance of DeterministicChunkIdsPlugin.
|
|---|
| 29 | * @param {DeterministicChunkIdsPluginOptions=} options options
|
|---|
| 30 | */
|
|---|
| 31 | constructor(options = {}) {
|
|---|
| 32 | /** @type {DeterministicChunkIdsPluginOptions} */
|
|---|
| 33 | this.options = options;
|
|---|
| 34 | }
|
|---|
| 35 |
|
|---|
| 36 | /**
|
|---|
| 37 | * Applies the plugin by registering its hooks on the compiler.
|
|---|
| 38 | * @param {Compiler} compiler the compiler instance
|
|---|
| 39 | * @returns {void}
|
|---|
| 40 | */
|
|---|
| 41 | apply(compiler) {
|
|---|
| 42 | compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
|
|---|
| 43 | compilation.hooks.chunkIds.tap(PLUGIN_NAME, (chunks) => {
|
|---|
| 44 | const chunkGraph = compilation.chunkGraph;
|
|---|
| 45 | const context = this.options.context
|
|---|
| 46 | ? this.options.context
|
|---|
| 47 | : compiler.context;
|
|---|
| 48 | const maxLength = this.options.maxLength || 3;
|
|---|
| 49 |
|
|---|
| 50 | const compareNatural = compareChunksNatural(chunkGraph);
|
|---|
| 51 |
|
|---|
| 52 | const usedIds = getUsedChunkIds(compilation);
|
|---|
| 53 | assignDeterministicIds(
|
|---|
| 54 | [...chunks].filter((chunk) => chunk.id === null),
|
|---|
| 55 | (chunk) =>
|
|---|
| 56 | getFullChunkName(chunk, chunkGraph, context, compiler.root),
|
|---|
| 57 | compareNatural,
|
|---|
| 58 | (chunk, id) => {
|
|---|
| 59 | const size = usedIds.size;
|
|---|
| 60 | usedIds.add(`${id}`);
|
|---|
| 61 | if (size === usedIds.size) return false;
|
|---|
| 62 | chunk.id = id;
|
|---|
| 63 | chunk.ids = [id];
|
|---|
| 64 | return true;
|
|---|
| 65 | },
|
|---|
| 66 | [10 ** maxLength],
|
|---|
| 67 | 10,
|
|---|
| 68 | usedIds.size
|
|---|
| 69 | );
|
|---|
| 70 | });
|
|---|
| 71 | });
|
|---|
| 72 | }
|
|---|
| 73 | }
|
|---|
| 74 |
|
|---|
| 75 | module.exports = DeterministicChunkIdsPlugin;
|
|---|