|
6 | 6 | */ |
7 | 7 |
|
8 | 8 | import { createHash } from "crypto"; |
9 | | -import type { AssetInfo, Chunk, Compilation, Compiler, sources } from "webpack"; |
| 9 | +import type { |
| 10 | + AssetInfo, |
| 11 | + Chunk, |
| 12 | + Compilation, |
| 13 | + Compiler, |
| 14 | + sources, |
| 15 | + Module, |
| 16 | +} from "webpack"; |
10 | 17 | import { sep } from "path"; |
11 | 18 | import type { HtmlTagObject } from "./types"; |
12 | 19 |
|
13 | 20 | export type ChunkGroup = ReturnType<Compilation["addChunkInGroup"]>; |
14 | 21 |
|
15 | 22 | export const sriHashVariableReference = "__webpack_require__.sriHashes"; |
16 | 23 |
|
| 24 | +export const miniCssExtractType = "css/mini-extract"; |
| 25 | + |
17 | 26 | export function assert(value: unknown, message: string): asserts value { |
18 | 27 | if (!value) { |
19 | 28 | throw new Error(message); |
@@ -112,13 +121,28 @@ export function notNil<TValue>( |
112 | 121 | return value !== null && value !== undefined; |
113 | 122 | } |
114 | 123 |
|
| 124 | +export function hasMiniCssExtractModlue(modules: Module[]) { |
| 125 | + return modules.find((module) => module.type === miniCssExtractType); |
| 126 | +} |
| 127 | + |
115 | 128 | export function generateSriHashPlaceholders( |
| 129 | + compilation: Compilation, |
116 | 130 | chunks: Iterable<Chunk>, |
117 | 131 | hashFuncNames: [string, ...string[]] |
118 | 132 | ): Record<string, string> { |
119 | 133 | return Array.from(chunks).reduce((sriHashes, depChunk: Chunk) => { |
120 | 134 | if (depChunk.id) { |
121 | | - sriHashes[depChunk.id] = makePlaceholder(hashFuncNames, depChunk.id); |
| 135 | + const modules = compilation.chunkGraph.getChunkModules(depChunk); |
| 136 | + const containCssModule = hasMiniCssExtractModlue(modules); |
| 137 | + if (containCssModule) { |
| 138 | + sriHashes[`${depChunk.id}_${miniCssExtractType}`] = makePlaceholder( |
| 139 | + hashFuncNames, |
| 140 | + `${depChunk.id}_${miniCssExtractType}` |
| 141 | + ); |
| 142 | + } |
| 143 | + if (!containCssModule || (containCssModule && modules.length > 1)) { |
| 144 | + sriHashes[depChunk.id] = makePlaceholder(hashFuncNames, depChunk.id); |
| 145 | + } |
122 | 146 | } |
123 | 147 | return sriHashes; |
124 | 148 | }, {} as { [key: string]: string }); |
@@ -291,3 +315,17 @@ export function hasOwnProperty<X extends object, Y extends PropertyKey>( |
291 | 315 | ): obj is X & Record<Y, unknown> { |
292 | 316 | return Object.prototype.hasOwnProperty.call(obj, prop); |
293 | 317 | } |
| 318 | + |
| 319 | +export const normalizeChunkId = ( |
| 320 | + sourcePath: string, |
| 321 | + chunk: Chunk, |
| 322 | + compilation: Compilation |
| 323 | +) => { |
| 324 | + if ( |
| 325 | + sourcePath.endsWith(".css") && |
| 326 | + hasMiniCssExtractModlue(compilation.chunkGraph.getChunkModules(chunk)) |
| 327 | + ) { |
| 328 | + return `${chunk.id}_${miniCssExtractType}`; |
| 329 | + } |
| 330 | + return chunk.id as string | number; |
| 331 | +}; |
0 commit comments