Search code examples
typescriptvuejs3assetsidiomsvite

How to dynamically point to a static asset leveraging the path lookup in Vite/Vue3? Using Typescript paths in dynamic URLs to assets


It is my understanding that as per the docs, following is the idiomatic way to dynamically generate an url to a static asset with Vite/Vue3:

URL(`../../assets/${name}.png`, import.meta.url).href

However, I would like to leverage the TypeScript import lookup locations as per tsconfig.json

  "compilerOptions": {
    "paths": {
      "@/*": ["./src/*"]
    }

Trying a simple

URL(`@/assets/${name}.png`, import.meta.url).href

will just put the @ in the url. Using src/assets/${name}.png works but defeats the purpose.

It also seems that URL will gladly generate any kind of string without checking whether it points to a resource that could actually be loaded by the browser.

What is the idiomatic way to dynamically point to a static asset leveraging the path lookup?


Solution

  • Using new URL won't work because this code isn't statically replaced by Vite, so you won't be able to use your aliases.

    You can use import.meta.globEager instead.

    const images = import.meta.globEager('@/assets/*.png', { as: 'url' })
    

    This will give you an object, which keys are the paths to the images and the values are their URLs.

    An example would be:

    const images = import.meta.globEager('@/assets/*.png', { as: 'url' });
    
    function assetUrl(name: string): string {
      return images[Object.keys(images).find((path) => path.endsWith(name))]?.default;
    }