Skip to content

Commit

Permalink
fix: leave fully dynamic import.meta.url asset (fixes #10306) (#10549)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Apr 2, 2023
1 parent fdef8fd commit 56802b1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
12 changes: 10 additions & 2 deletions packages/vite/src/node/plugins/assetImportMetaUrl.ts
Expand Up @@ -56,15 +56,23 @@ export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
const ast = this.parse(rawUrl)
const templateLiteral = (ast as any).body[0].expression
if (templateLiteral.expressions.length) {
const pattern = JSON.stringify(buildGlobPattern(templateLiteral))
const pattern = buildGlobPattern(templateLiteral)
if (pattern.startsWith('**')) {
// don't transform for patterns like this
// because users won't intend to do that in most cases
continue
}

// Note: native import.meta.url is not supported in the baseline
// target so we use the global location here. It can be
// window.location or self.location in case it is used in a Web Worker.
// @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
s.update(
index,
index + exp.length,
`new URL((import.meta.glob(${pattern}, { eager: true, import: 'default', as: 'url' }))[${rawUrl}], self.location)`,
`new URL((import.meta.glob(${JSON.stringify(
pattern,
)}, { eager: true, import: 'default', as: 'url' }))[${rawUrl}], self.location)`,
)
continue
}
Expand Down
19 changes: 16 additions & 3 deletions playground/assets/index.html
Expand Up @@ -226,6 +226,11 @@ <h2>new URL(`non-existent`, import.meta.url)</h2>
<code class="non-existent-import-meta-url"></code>
</p>

<h2>new URL(`${dynamic}`, import.meta.url)</h2>
<p>
<code class="dynamic-import-meta-url-all"></code>
</p>

<h2>simple script tag import-expression</h2>
<code class="import-expression"></code>
<code class="obj-import-express"></code>
Expand Down Expand Up @@ -427,9 +432,17 @@ <h3>assets in noscript</h3>
testDynamicImportMetaUrlWithComma('icon', 1)
testDynamicImportMetaUrlWithComma('asset', 2)

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

{
const name = './nested/icon'
const metaUrl = new URL(`${name}.png`, import.meta.url)
text(`.dynamic-import-meta-url-all`, metaUrl)
}

function text(el, text) {
document.querySelector(el).textContent = text
Expand Down

0 comments on commit 56802b1

Please sign in to comment.