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

Dynamic image url import error in vite 6 #19252

Closed
7 tasks done
lmsccc opened this issue Jan 21, 2025 · 1 comment
Closed
7 tasks done

Dynamic image url import error in vite 6 #19252

lmsccc opened this issue Jan 21, 2025 · 1 comment

Comments

@lmsccc
Copy link

lmsccc commented Jan 21, 2025

Describe the bug

In vite 5, I am able to use dynamic import in the following way:

// path like "icon/react.png"
function getImageUrl(path) {
  return new URL(`./dir/${path}`, import.meta.url).href
}

However, in vite 6, it does not work. I have noticed that someone has the same question at #19156. I can solve it like this:

export function getImageUrl(imgPath: string) {
  const paths = imgPath.split('/');
  return new URL(`../assets/${paths[0]}/${paths[1]}`, import.meta.url).href;
}

But I believe this is not an ideal solution as it implies that the path level is limited. Is there any other way to address this problem?

Reproduction

https://stackblitz.com/edit/vitejs-vite-pqyje2us?file=src%2Fmain.js,package.json&terminal=dev

Steps to reproduce

No response

System Info

vite 6.0.7
node 18.20.2

Used Package Manager

npm

Logs

No response

Validations

@hi-ogawa
Copy link
Collaborator

As explained in #19156 (comment), this is an intended change/fix.

The alternative suggested is to use import.meta.glob. Probably you can try something like this:
https://stackblitz.com/edit/vitejs-vite-uhgyadyd?file=src%2Fmain.js

const glob = import.meta.glob('/src/assets/**/*', {
  query: '?url',
  eager: true,
});
app.innerHTML = `<pre>${JSON.stringify(glob, null, 2)}</pre>`;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants