Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/vite/src/node/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,16 @@ export interface Plugin extends RollupPlugin {
ctx: HmrContext
): Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>

/**
* Resolve an asset's public URL. This hook can call `this.emitFile` and
* return `__VITE_ASSET__${emitFileResult}__` to be replaced by Vite
* later in the build.
*/
resolveBuiltUrl?(
this: PluginContext,
url: string
): Promise<string | null | undefined> | string | null | undefined

/**
* extend hooks with ssr flag
*/
Expand Down
43 changes: 38 additions & 5 deletions packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,15 +128,16 @@ export function checkPublicFile(
}
}

export function fileToUrl(
export async function fileToUrl(
id: string,
config: ResolvedConfig,
ctx: PluginContext
): string | Promise<string> {
): Promise<string> {
if (config.command === 'serve') {
return fileToDevUrl(id, config)
} else {
return fileToBuiltUrl(id, config, ctx)
const builtUrl = await resolveBuiltUrl(id, config, ctx)
return builtUrl || fileToBuiltUrl(id, config, ctx)
}
}

Expand Down Expand Up @@ -252,19 +253,51 @@ export async function urlToBuiltUrl(
url: string,
importer: string,
config: ResolvedConfig,
pluginContext: PluginContext
ctx: PluginContext
): Promise<string> {
const builtUrl = await resolveBuiltUrl(url, config, ctx)
if (builtUrl) {
return builtUrl
}

if (checkPublicFile(url, config)) {
return config.base + url.slice(1)
}

const file = url.startsWith('/')
? path.join(config.root, url)
: path.join(path.dirname(importer), url)

return fileToBuiltUrl(
file,
config,
pluginContext,
ctx,
// skip public check since we just did it above
true
)
}

async function resolveBuiltUrl(
url: string,
config: ResolvedConfig,
ctx: PluginContext
): Promise<string | undefined> {
for (const { resolveBuiltUrl } of config.plugins) {
if (resolveBuiltUrl) {
const builtUrl = await resolveBuiltUrl.call(ctx, url)
if (builtUrl) {
const match = builtUrl.match(/^__VITE_ASSET__(.+?)__/)
if (match) {
let map = assetHashToFilenameMap.get(config)
if (!map) {
map = new Map()
assetHashToFilenameMap.set(config, map)
}
const contentHash = match[1]
map.set(contentHash, ctx.getFileName(contentHash))
}
return builtUrl
}
}
}
}