Skip to content

Commit

Permalink
feat: add resolveBuiltUrl hook
Browse files Browse the repository at this point in the history
For rewriting the public URLs of static assets.
  • Loading branch information
aleclarson committed Apr 19, 2021
1 parent 70536b4 commit a02eb2c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
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
33 changes: 28 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,41 @@ 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
) {
for (const { resolveBuiltUrl } of config.plugins) {
if (resolveBuiltUrl) {
const result = await resolveBuiltUrl.call(ctx, url)
if (result) {
return result
}
}
}
}

0 comments on commit a02eb2c

Please sign in to comment.