Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: support dynamic path with alias in new URL() (fix #10597) #10743

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
23 changes: 20 additions & 3 deletions packages/vite/src/node/plugins/assetImportMetaUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { preloadHelperId } from './importAnalysisBuild'
export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
const normalizedPublicDir = normalizePath(config.publicDir)
let assetResolver: ResolveFn
let aliaResolver: ResolveFn
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

aliasResolver

Suggested change
let aliaResolver: ResolveFn
let aliasResolver: ResolveFn


return {
name: 'vite:asset-import-meta-url',
Expand Down Expand Up @@ -64,6 +65,22 @@ export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
const ast = this.parse(pureUrl)
const templateLiteral = (ast as any).body[0].expression
if (templateLiteral.expressions.length) {
let newUrl: string | undefined
// rawUrl could include alias, try to resolve it
aliaResolver ??= config.createResolver()
const resolvedUrl = await aliaResolver(
Comment on lines +70 to +71
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
aliaResolver ??= config.createResolver()
const resolvedUrl = await aliaResolver(
aliasResolver ??= config.createResolver()
const resolvedUrl = await aliasResolver(

rawUrl.slice(1),
undefined,
true,
)
if (resolvedUrl) {
newUrl = normalizePath(path.relative(config.root, resolvedUrl))
if (!newUrl.startsWith('.')) {
newUrl = `/${newUrl}`
}
newUrl = '`' + newUrl
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are you making this assignment?

}

const pattern = buildGlobPattern(templateLiteral)
if (pattern.startsWith('**')) {
// don't transform for patterns like this
Expand All @@ -86,9 +103,9 @@ export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
index + exp.length,
`new URL((import.meta.glob(${JSON.stringify(
pattern,
)}, ${JSON.stringify(
globOptions,
)}))[${pureUrl}], self.location)`,
)}, ${JSON.stringify(globOptions)}))[${
newUrl ?? pureUrl
}], self.location)`,
)
continue
}
Expand Down
12 changes: 12 additions & 0 deletions playground/assets/__tests__/assets.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,18 @@ test('new URL(`./${dynamic}?abc`, import.meta.url)', async () => {
)
})

test('new URL(`@/${dynamic}`, import.meta.url)', async () => {
expect(await page.textContent('.dynamic-import-meta-url-1-alias')).toMatch(
isBuild ? 'data:image/png;base64' : '/foo/nested/icon.png',
)
expect(await page.textContent('.dynamic-import-meta-url-2-alias')).toMatch(
assetMatch,
)
expect(await page.textContent('.dynamic-import-meta-url-js-alias')).toMatch(
isBuild ? 'data:application/javascript;base64' : '/foo/nested/test.js',
)
})

test('new URL(`non-existent`, import.meta.url)', async () => {
expect(await page.textContent('.non-existent-import-meta-url')).toMatch(
new URL('non-existent', page.url()).pathname,
Expand Down
27 changes: 27 additions & 0 deletions playground/assets/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,19 @@ <h2>new URL(`./${dynamic}?abc`, import.meta.url)</h2>
<code class="dynamic-import-meta-url-2-query"></code>
</p>

<h2>new URL(`@/${dynamic}`, import.meta.url)</h2>
<p>
<img class="dynamic-import-meta-url-img-1-alias" />
<code class="dynamic-import-meta-url-1-alias"></code>
</p>
<p>
<img class="dynamic-import-meta-url-img-2-alias" />
<code class="dynamic-import-meta-url-2-alias"></code>
</p>
<p>
<code class="dynamic-import-meta-url-js-alias"></code>
</p>

<h2>new URL(`non-existent`, import.meta.url)</h2>
<p>
<code class="non-existent-import-meta-url"></code>
Expand Down Expand Up @@ -453,10 +466,24 @@ <h3>assets in noscript</h3>
testDynamicImportMetaUrlWithQuery('icon', 1)
testDynamicImportMetaUrlWithQuery('asset', 2)

function testDynamicImportMetaUrlWithAlias(name, i) {
const metaUrl = new URL(`@/${name}.png`, import.meta.url)
text(`.dynamic-import-meta-url-${i}-alias`, metaUrl)
document.querySelector(`.dynamic-import-meta-url-img-${i}-alias`).src =
metaUrl
}

testDynamicImportMetaUrlWithAlias('icon', 1)
testDynamicImportMetaUrlWithAlias('asset', 2)

{
const name = 'test'

const js = new URL(`./nested/${name}.js`, import.meta.url).href
text('.dynamic-import-meta-url-js', js)

const aliasedJs = new URL(`@/${name}.js`, import.meta.url).href
text('.dynamic-import-meta-url-js-alias', aliasedJs)
}

{
Expand Down