( pluginContext: PluginContext, chunk: RenderedChunk, opts: NormalizedOutputOptions, code: string, )
| 74 | } |
| 75 | |
| 76 | export function renderAssetUrlInJS( |
| 77 | pluginContext: PluginContext, |
| 78 | chunk: RenderedChunk, |
| 79 | opts: NormalizedOutputOptions, |
| 80 | code: string, |
| 81 | ): MagicString | undefined { |
| 82 | const { environment } = pluginContext |
| 83 | const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime( |
| 84 | opts.format, |
| 85 | environment.config.isWorker, |
| 86 | ) |
| 87 | |
| 88 | let match: RegExpExecArray | null |
| 89 | let s: MagicString | undefined |
| 90 | |
| 91 | // Urls added with JS using e.g. |
| 92 | // imgElement.src = "__VITE_ASSET__5aA0Ddc0__" are using quotes |
| 93 | |
| 94 | // Urls added in CSS that is imported in JS end up like |
| 95 | // var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aA0Ddc0__)}\n"; |
| 96 | |
| 97 | // In both cases, the wrapping should already be fine |
| 98 | |
| 99 | assetUrlRE.lastIndex = 0 |
| 100 | while ((match = assetUrlRE.exec(code))) { |
| 101 | s ||= new MagicString(code) |
| 102 | const [full, referenceId, postfix = ''] = match |
| 103 | const file = pluginContext.getFileName(referenceId) |
| 104 | chunk.viteMetadata!.importedAssets.add(cleanUrl(file)) |
| 105 | const filename = file + postfix |
| 106 | const replacement = toOutputFilePathInJS( |
| 107 | environment, |
| 108 | filename, |
| 109 | 'asset', |
| 110 | chunk.fileName, |
| 111 | 'js', |
| 112 | toRelativeRuntime, |
| 113 | ) |
| 114 | const replacementString = |
| 115 | typeof replacement === 'string' |
| 116 | ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) |
| 117 | : `"+${replacement.runtime}+"` |
| 118 | s.update(match.index, match.index + full.length, replacementString) |
| 119 | } |
| 120 | |
| 121 | // Replace __VITE_PUBLIC_ASSET__5aA0Ddc0__ with absolute paths |
| 122 | |
| 123 | const publicAssetUrlMap = publicAssetUrlCache.get( |
| 124 | environment.getTopLevelConfig(), |
| 125 | )! |
| 126 | publicAssetUrlRE.lastIndex = 0 |
| 127 | while ((match = publicAssetUrlRE.exec(code))) { |
| 128 | s ||= new MagicString(code) |
| 129 | const [full, hash] = match |
| 130 | const publicUrl = publicAssetUrlMap.get(hash)!.slice(1) |
| 131 | const replacement = toOutputFilePathInJS( |
| 132 | environment, |
| 133 | publicUrl, |
no test coverage detected