Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(asset): allow non-existent url (#7306)
  • Loading branch information
bluwy committed Mar 13, 2022
1 parent cfc7648 commit 6bc45a2
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 3 deletions.
6 changes: 6 additions & 0 deletions packages/playground/assets/__tests__/assets.spec.ts
Expand Up @@ -232,6 +232,12 @@ test('new URL(`${dynamic}`, import.meta.url)', async () => {
)
})

test('new URL(`non-existent`, import.meta.url)', async () => {
expect(await page.textContent('.non-existent-import-meta-url')).toMatch(
'/foo/non-existent'
)
})

if (isBuild) {
test('manifest', async () => {
const manifest = readManifest('foo')
Expand Down
8 changes: 8 additions & 0 deletions packages/playground/assets/index.html
Expand Up @@ -166,6 +166,11 @@ <h2>new URL(`./${dynamic}`, import.meta.url,) (with comma)</h2>
<code class="dynamic-import-meta-url-2-comma"></code>
</p>

<h2>new URL(`non-existent`, import.meta.url)</h2>
<p>
<code class="non-existent-import-meta-url"></code>
</p>

<h2>simple script tag import-expression</h2>
<code class="import-expression"></code>
<script>
Expand Down Expand Up @@ -257,6 +262,9 @@ <h3 class="foo-public">
document.querySelector('.import-meta-url-img-comma-nl').src =
metaUrlWithCommaNL

const metaUrlNonExistent = new URL('non-existent', import.meta.url).pathname
text('.non-existent-import-meta-url', metaUrlNonExistent)

/**
* don't process the code in the comment
* const url = new URL('non_existent_file.png', import.meta.url)
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugins/asset.ts
Expand Up @@ -146,11 +146,11 @@ 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 {
Expand Down
9 changes: 8 additions & 1 deletion packages/vite/src/node/plugins/assetImportMetaUrl.ts
Expand Up @@ -59,7 +59,14 @@ export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin {

const url = rawUrl.slice(1, -1)
const file = path.resolve(path.dirname(id), url)
const builtUrl = await fileToUrl(file, config, this)
// Get final asset URL. Catch error if the file does not exist,
// in which we can resort to the initial URL and let it resolve in runtime
const builtUrl = await fileToUrl(file, config, this).catch(() => {
config.logger.warnOnce(
`${exp} doesn't exist at build time, it will remain unchanged to be resolved at runtime`
)
return url
})
s.overwrite(
index,
index + exp.length,
Expand Down

0 comments on commit 6bc45a2

Please sign in to comment.