Skip to content

Commit 4366ac4

Browse files
authored
feat: use import.meta.ROLLDOWN_FILE_URL_* for assets in JS (#22888)
1 parent a6c08e1 commit 4366ac4

2 files changed

Lines changed: 149 additions & 16 deletions

File tree

‎packages/vite/src/node/constants.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export const ROLLUP_HOOKS: RollupPluginHooks[] = [
1717
'augmentChunkHash',
1818
'outputOptions',
1919
// 'renderDynamicImport',
20-
// 'resolveFileUrl',
20+
'resolveFileUrl',
2121
// 'resolveImportMeta',
2222
'intro',
2323
'outro',

‎packages/vite/src/node/plugins/asset.ts‎

Lines changed: 148 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,35 @@ const jsSourceMapRE = /\.[cm]?js\.map$/
5252
export const noInlineRE: RegExp = /[?&]no-inline\b/
5353
export const inlineRE: RegExp = /[?&]inline\b/
5454

55-
const assetCache = new WeakMap<Environment, Map<string, string>>()
55+
/**
56+
* The resolved form of an asset request during build.
57+
* - `string`: a URL usable as-is (an inlined `data:` URL, a
58+
* `__VITE_PUBLIC_ASSET__` token, or a bundled-dev output URL).
59+
* - `reference`: an emitted file referenced by its `referenceId`, to be turned
60+
* into `import.meta.ROLLDOWN_FILE_URL_<referenceId>` (JS) or a `__VITE_ASSET__`
61+
* token (CSS/HTML). The `postfix` is the query/hash appended after the URL.
62+
*/
63+
type FileToBuiltUrlResult =
64+
| { type: 'string'; value: string }
65+
| { type: 'reference'; referenceId: string; postfix: string }
66+
67+
/**
68+
* How an asset URL should be embedded by the caller:
69+
* - `'string'`: plain text (CSS/HTML and other text consumers)
70+
* - `'js'`: a JavaScript expression (embedded in generated JS)
71+
*/
72+
type AssetUrlFormat = 'string' | 'js'
73+
74+
const assetCache = new WeakMap<Environment, Map<string, FileToBuiltUrlResult>>()
75+
76+
/**
77+
* Emitted asset file names referenced from each chunk (keyed by preliminary
78+
* chunk name) via `import.meta.ROLLDOWN_FILE_URL_<referenceId>`.
79+
*/
80+
const importedAssetsFromFileUrl = new WeakMap<
81+
Environment,
82+
Map<string, Set<string>>
83+
>()
5684

5785
/** a set of referenceId for entry CSS assets for each environment */
5886
export const cssEntriesMap: WeakMap<
@@ -219,18 +247,33 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
219247
}
220248

221249
id = removeUrlQuery(id)
222-
let url = await fileToUrl(this, id)
250+
let resolved: FileToBuiltUrlResult
251+
if (!this.environment.config.isBundled) {
252+
resolved = {
253+
type: 'string',
254+
value: await fileToDevUrl(this.environment, id),
255+
}
256+
} else {
257+
resolved = await resolveBuiltAsset(this, id)
258+
}
223259

224260
// Inherit HMR timestamp if this asset was invalidated
225-
if (!url.startsWith('data:') && this.environment.mode === 'dev') {
261+
if (
262+
resolved.type === 'string' &&
263+
!resolved.value.startsWith('data:') &&
264+
this.environment.mode === 'dev'
265+
) {
226266
const mod = this.environment.moduleGraph.getModuleById(id)
227267
if (mod && mod.lastHMRTimestamp > 0) {
228-
url = injectQuery(url, `t=${mod.lastHMRTimestamp}`)
268+
resolved = {
269+
type: 'string',
270+
value: injectQuery(resolved.value, `t=${mod.lastHMRTimestamp}`),
271+
}
229272
}
230273
}
231274

232275
return {
233-
code: `export default ${JSON.stringify(encodeURIPath(url))}`,
276+
code: `export default ${formatBuiltAsset(resolved, 'js')}`,
234277
// Force rollup to keep this module from being shared between other entry points if it's an entrypoint.
235278
// If the resulting chunk is empty, it will be removed in generateBundle.
236279
moduleSideEffects:
@@ -245,7 +288,48 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
245288

246289
...(config.command === 'build'
247290
? {
291+
resolveFileUrl({ fileName, chunkId, format }) {
292+
const { environment } = this
293+
294+
let importedByChunk = importedAssetsFromFileUrl.get(environment)
295+
if (!importedByChunk) {
296+
importedByChunk = new Map()
297+
importedAssetsFromFileUrl.set(environment, importedByChunk)
298+
}
299+
let files = importedByChunk.get(chunkId)
300+
if (!files) {
301+
files = new Set()
302+
importedByChunk.set(chunkId, files)
303+
}
304+
files.add(cleanUrl(fileName))
305+
306+
const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(
307+
format,
308+
environment.config.isWorker,
309+
)
310+
const replacement = toOutputFilePathInJS(
311+
environment,
312+
fileName,
313+
'asset',
314+
chunkId,
315+
'js',
316+
toRelativeRuntime,
317+
)
318+
return typeof replacement === 'string'
319+
? JSON.stringify(encodeURIPath(replacement))
320+
: replacement.runtime
321+
},
322+
248323
renderChunk(code, chunk, opts) {
324+
const importedFromFileUrl = importedAssetsFromFileUrl
325+
.get(this.environment)
326+
?.get(chunk.fileName)
327+
if (importedFromFileUrl) {
328+
for (const file of importedFromFileUrl) {
329+
chunk.viteMetadata!.importedAssets.add(file)
330+
}
331+
}
332+
249333
const s = renderAssetUrlInJS(this, chunk, opts, code)
250334

251335
if (s) {
@@ -332,7 +416,7 @@ export async function fileToUrl(
332416
if (!environment.config.isBundled) {
333417
return fileToDevUrl(environment, id, asFileUrl)
334418
} else {
335-
return fileToBuiltUrl(pluginContext, id)
419+
return fileToBuiltUrl(pluginContext, id, 'string')
336420
}
337421
}
338422

@@ -425,15 +509,54 @@ function isGitLfsPlaceholder(content: Buffer): boolean {
425509
}
426510

427511
/**
428-
* Register an asset to be emitted as part of the bundle (if necessary)
429-
* and returns the resolved public URL
512+
* Register an asset to be emitted as part of the bundle (if necessary) and
513+
* return its resolved URL in the requested `format`.
430514
*/
431515
async function fileToBuiltUrl(
432516
pluginContext: PluginContext,
433517
id: string,
518+
format: AssetUrlFormat,
434519
skipPublicCheck = false,
435520
forceInline?: boolean,
436521
): Promise<string> {
522+
const resolved = await resolveBuiltAsset(
523+
pluginContext,
524+
id,
525+
skipPublicCheck,
526+
forceInline,
527+
)
528+
return formatBuiltAsset(resolved, format)
529+
}
530+
531+
/** Format a resolved asset as either a JS expression or a plain-text string. */
532+
function formatBuiltAsset(
533+
resolved: FileToBuiltUrlResult,
534+
format: AssetUrlFormat,
535+
): string {
536+
if (resolved.type === 'reference') {
537+
if (format === 'js') {
538+
const base = `import.meta.ROLLDOWN_FILE_URL_${resolved.referenceId}`
539+
return resolved.postfix
540+
? `${base} + ${JSON.stringify(resolved.postfix)}`
541+
: base
542+
}
543+
return `__VITE_ASSET__${resolved.referenceId}__${resolved.postfix}`
544+
}
545+
return format === 'js'
546+
? JSON.stringify(encodeURIPath(resolved.value))
547+
: resolved.value
548+
}
549+
550+
/**
551+
* Register an asset to be emitted (if necessary) and return the structured result,
552+
* cached per id so the emitted file is shared.
553+
*/
554+
async function resolveBuiltAsset(
555+
pluginContext: PluginContext,
556+
id: string,
557+
skipPublicCheck = false,
558+
forceInline?: boolean,
559+
): Promise<FileToBuiltUrlResult> {
437560
const environment = pluginContext.environment
438561
const topLevelConfig = environment.getTopLevelConfig()
439562
if (!skipPublicCheck) {
@@ -443,7 +566,10 @@ async function fileToBuiltUrl(
443566
// If inline via query, re-assign the id so it can be read by the fs and inlined
444567
id = publicFile
445568
} else {
446-
return publicFileToBuiltUrl(id, topLevelConfig)
569+
return {
570+
type: 'string',
571+
value: publicFileToBuiltUrl(id, topLevelConfig),
572+
}
447573
}
448574
}
449575
}
@@ -457,11 +583,14 @@ async function fileToBuiltUrl(
457583
let { file, postfix } = splitFileAndPostfix(id)
458584
const content = await fsp.readFile(file)
459585

460-
let url: string
586+
let result: FileToBuiltUrlResult
461587
if (
462588
shouldInline(environment, file, id, content, pluginContext, forceInline)
463589
) {
464-
url = assetToDataURL(environment, file, content)
590+
result = {
591+
type: 'string',
592+
value: assetToDataURL(environment, file, content),
593+
}
465594
} else {
466595
// emit as asset
467596
const originalFileName = normalizePath(
@@ -484,14 +613,17 @@ async function fileToBuiltUrl(
484613
environment.config.isBundled
485614
) {
486615
const outputFilename = pluginContext.getFileName(referenceId)
487-
url = toOutputFilePathInJSForBundledDev(environment, outputFilename)
616+
result = {
617+
type: 'string',
618+
value: toOutputFilePathInJSForBundledDev(environment, outputFilename),
619+
}
488620
} else {
489-
url = `__VITE_ASSET__${referenceId}__${postfix}`
621+
result = { type: 'reference', referenceId, postfix }
490622
}
491623
}
492624

493-
cache.set(id, url)
494-
return url
625+
cache.set(id, result)
626+
return result
495627
}
496628

497629
export function toOutputFilePathInJSForBundledDev(
@@ -533,6 +665,7 @@ export async function urlToBuiltUrl(
533665
return fileToBuiltUrl(
534666
pluginContext,
535667
file,
668+
'string',
536669
// skip public check since we just did it above
537670
true,
538671
forceInline,

0 commit comments

Comments
 (0)