docs: clarify dynamic new URL(foo, import.meta.url) behavior (#18587)

This commit is contained in:
翠 / green 2024-11-06 18:32:49 +09:00 committed by GitHub
parent f08b1463db
commit d969d4db91
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -135,6 +135,7 @@ This pattern also supports dynamic URLs via template literals:
```js
function getImageUrl(name) {
// note that this does not include files in subdirectories
return new URL(`./dir/${name}.png`, import.meta.url).href
}
```
@ -146,6 +147,25 @@ During the production build, Vite will perform necessary transforms so that the
const imgUrl = new URL(imagePath, import.meta.url).href
```
::: details How it works
Vite will transform the `getImageUrl` function to:
```js
import __img0png from './dir/img0.png'
import __img1png from './dir/img1.png'
function getImageUrl(name) {
const modules = {
'./dir/img0.png': __img0png,
'./dir/img1.png': __img1png,
}
return new URL(modules[`./dir/${name}.png`], import.meta.url).href
}
```
:::
::: warning Does not work with SSR
This pattern does not work if you are using Vite for Server-Side Rendering, because `import.meta.url` have different semantics in browsers vs. Node.js. The server bundle also cannot determine the client host URL ahead of time.
:::