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

new URL() with import.meta.url Fails to Resolve Paths Correctly in Vite 6 #19156

Closed
7 tasks done
tom-style opened this issue Jan 7, 2025 · 3 comments
Closed
7 tasks done

Comments

@tom-style
Copy link

Describe the bug

export function getImg(url: string) { return new URL(/src/assets/imgs/${url}`, import.meta.url).href;
}

const logo = getImg('login/logo.svg');
`

Vite 5 Behavior: The function correctly resolves the path.
Vite 6 Behavior: The function fails to resolve the path correctly.

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

pnpm

Logs

No response

Validations

@sapphi-red
Copy link
Member

sapphi-red commented Jan 7, 2025

This was a bug in Vite 5.x. Variables inside new URL(`./something/${var}`, import.meta.url) was incorrectly matching nested files.
https://vite.dev/guide/assets.html#:~:text=function%20getImageUrl(name)%20%7B%0A%20%20//%20note%20that%20this%20does%20not%20include%20files%20in%20subdirectories%0A%20%20return%20new%20URL(%60./dir/%24%7Bname%7D.png%60%2C%20import.meta.url).href%0A%7D
This is because the previous behavior could unintentionally pull in too many files.

To achieve the previous behavior, you can make the split the variable:

const t2 = 'login/eraser.png'.split('/');
app.append(new URL(`/src/assets/imgs/${t2[0]}/${t2[1]}`, import.meta.url).href);

or use import.meta.glob.

@lmsccc
Copy link

lmsccc commented Jan 20, 2025

There is still a problem. In vite5, the result returned by getImg will match the static resource file name processed by assetFileNames in the vite build configuration, but in vite6, they are not the same, resulting in static resource loading failure. @sapphi-red ,This is my config

          assetFileNames: ({ names }) => {
            const name = names[0];
            if (/\.(gif|jpe?g|png|svg)$/.test(name ?? '')) {
              return 'assets/media/[name]-[hash][extname]';
            }
            if (/\.css$/.test(name ?? '')) {
              return 'assets/css/[name]-[hash][extname]';
            }
            // default value
            // ref: https://rollupjs.org/guide/en/#outputassetfilenames
            return 'assets/[name]-[hash][extname]';
          },

@patak-dev
Copy link
Member

@lmsccc please create a new issue with a minimal reproduction so we can track your report

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

4 participants