( config: ResolvedConfig, )
| 1203 | * Move importmap before the first module script and modulepreload link |
| 1204 | */ |
| 1205 | export function postImportMapHook( |
| 1206 | config: ResolvedConfig, |
| 1207 | ): IndexHtmlTransformHook { |
| 1208 | const decoder = new TextDecoder() |
| 1209 | return function (html, { bundle }) { |
| 1210 | const chunkImportMapEnabled = |
| 1211 | config.command === 'build' && config.build.chunkImportMap |
| 1212 | |
| 1213 | if (importMapAppendRE.test(html)) { |
| 1214 | let importMap: string | undefined |
| 1215 | html = html.replace(importMapRE, (match) => { |
| 1216 | importMap = match |
| 1217 | return '' |
| 1218 | }) |
| 1219 | |
| 1220 | if (importMap) { |
| 1221 | html = html.replace( |
| 1222 | importMapAppendRE, |
| 1223 | (match) => `${importMap}\n${match}`, |
| 1224 | ) |
| 1225 | if (chunkImportMapEnabled) { |
| 1226 | // https://caniuse.com/mdn-html_elements_script_type_importmap_multiple_import_maps |
| 1227 | this.warn( |
| 1228 | `The \`build.chunkImportMap\` option is enabled but an import map also exists in the input HTML file.` + |
| 1229 | ` This leads to multiple import maps generated in the output HTML, which is not supported by older browsers and Firefox.`, |
| 1230 | ) |
| 1231 | } |
| 1232 | } |
| 1233 | } |
| 1234 | |
| 1235 | if (chunkImportMapEnabled) { |
| 1236 | const nonce = config.html?.cspNonce |
| 1237 | const importMap = bundle![getImportMapFilename(config)] as OutputAsset |
| 1238 | const importMapHtml = serializeTag({ |
| 1239 | tag: 'script', |
| 1240 | attrs: { type: 'importmap', ...(nonce ? { nonce } : {}) }, |
| 1241 | children: |
| 1242 | typeof importMap.source === 'string' |
| 1243 | ? importMap.source |
| 1244 | : decoder.decode(importMap.source), |
| 1245 | }) |
| 1246 | if (importMapAppendRE.test(html)) { |
| 1247 | // NOTE: insert before the existing import map so that our import map takes precedence |
| 1248 | html = html.replace( |
| 1249 | importMapAppendRE, |
| 1250 | (match) => `${importMapHtml}\n${match}`, |
| 1251 | ) |
| 1252 | } else { |
| 1253 | html = `${importMapHtml}\n${html}` |
| 1254 | } |
| 1255 | } |
| 1256 | |
| 1257 | return html |
| 1258 | } |
| 1259 | } |
| 1260 | |
| 1261 | export function injectCspNonceMetaTagHook( |
| 1262 | config: ResolvedConfig, |
no test coverage detected