1 |
|
2 |
|
3 |
|
4 |
|
5 | "use strict";
|
6 | const EntrypointsOverSizeLimitWarning = require("./EntrypointsOverSizeLimitWarning");
|
7 | const AssetsOverSizeLimitWarning = require("./AssetsOverSizeLimitWarning");
|
8 | const NoAsyncChunksWarning = require("./NoAsyncChunksWarning");
|
9 |
|
10 | module.exports = class SizeLimitsPlugin {
|
11 | constructor(options) {
|
12 | this.hints = options.hints;
|
13 | this.maxAssetSize = options.maxAssetSize;
|
14 | this.maxEntrypointSize = options.maxEntrypointSize;
|
15 | this.assetFilter = options.assetFilter;
|
16 | }
|
17 | apply(compiler) {
|
18 | const entrypointSizeLimit = this.maxEntrypointSize;
|
19 | const assetSizeLimit = this.maxAssetSize;
|
20 | const hints = this.hints;
|
21 | const assetFilter = this.assetFilter || (asset => !asset.endsWith(".map"));
|
22 |
|
23 | compiler.hooks.afterEmit.tap("SizeLimitsPlugin", compilation => {
|
24 | const warnings = [];
|
25 |
|
26 | const getEntrypointSize = entrypoint =>
|
27 | entrypoint.getFiles().reduce((currentSize, file) => {
|
28 | if (assetFilter(file) && compilation.assets[file]) {
|
29 | return currentSize + compilation.assets[file].size();
|
30 | }
|
31 |
|
32 | return currentSize;
|
33 | }, 0);
|
34 |
|
35 | const assetsOverSizeLimit = [];
|
36 | for (const assetName of Object.keys(compilation.assets)) {
|
37 | if (!assetFilter(assetName)) {
|
38 | continue;
|
39 | }
|
40 |
|
41 | const asset = compilation.assets[assetName];
|
42 | const size = asset.size();
|
43 | if (size > assetSizeLimit) {
|
44 | assetsOverSizeLimit.push({
|
45 | name: assetName,
|
46 | size: size
|
47 | });
|
48 | asset.isOverSizeLimit = true;
|
49 | }
|
50 | }
|
51 |
|
52 | const entrypointsOverLimit = [];
|
53 | for (const pair of compilation.entrypoints) {
|
54 | const name = pair[0];
|
55 | const entry = pair[1];
|
56 | const size = getEntrypointSize(entry);
|
57 |
|
58 | if (size > entrypointSizeLimit) {
|
59 | entrypointsOverLimit.push({
|
60 | name: name,
|
61 | size: size,
|
62 | files: entry.getFiles().filter(assetFilter)
|
63 | });
|
64 | entry.isOverSizeLimit = true;
|
65 | }
|
66 | }
|
67 |
|
68 | if (hints) {
|
69 |
|
70 |
|
71 |
|
72 |
|
73 | if (assetsOverSizeLimit.length > 0) {
|
74 | warnings.push(
|
75 | new AssetsOverSizeLimitWarning(assetsOverSizeLimit, assetSizeLimit)
|
76 | );
|
77 | }
|
78 | if (entrypointsOverLimit.length > 0) {
|
79 | warnings.push(
|
80 | new EntrypointsOverSizeLimitWarning(
|
81 | entrypointsOverLimit,
|
82 | entrypointSizeLimit
|
83 | )
|
84 | );
|
85 | }
|
86 |
|
87 | if (warnings.length > 0) {
|
88 | const hasAsyncChunks =
|
89 | compilation.chunks.filter(chunk => !chunk.canBeInitial()).length >
|
90 | 0;
|
91 |
|
92 | if (!hasAsyncChunks) {
|
93 | warnings.push(new NoAsyncChunksWarning());
|
94 | }
|
95 |
|
96 | if (hints === "error") {
|
97 | compilation.errors.push(...warnings);
|
98 | } else {
|
99 | compilation.warnings.push(...warnings);
|
100 | }
|
101 | }
|
102 | }
|
103 | });
|
104 | }
|
105 | };
|