Using Aliases in a Javascript Function

50 views Asked by At

I have a function responsible for constructing URLs using relative paths, such as ../../assets/images/content/recipe/. I want to replace the ../../assets/images part with a Vite alias, but it doesn't work.

Here's my function:

const getSrc = ext => {
    return new URL(
        `@img/content/recipe/${props.recipe.image}${ext}`,
        import.meta.url
    ).href;
};

And here's Vite config for aliases:

'@img': fileURLToPath(
    new URL('./src/assets/images', import.meta.url)
),

I'm looking for a possible solution.

1

There are 1 answers

3
Crazynds On

The URL class is a standart class in JS and not Vite. Ref: https://developer.mozilla.org/en-US/docs/Web/API/URL/URL

The way I use alias is like this: (vite.config.js)

import { resolve } from 'path'

        resolve: {
            alias: {
                '@img': resolve(__dirname, './src/assets/images'),
            },
        },

And to get a image you need to use import:

import Image from '@img/content/recipe/img.png'

Another thing is that you cannot import some image that is not resolved at Vite compile time, because if you create a file called img2.png after vite compilation, your JS will not know how to get this image. You will probably need to use a server to handle these images dynamically, or provide this imagens in a public path.

If you had all the images you need in compilation time, you can import dynamically using import.meta.glob('@img/content/*.png') and get the correct image using a search.

https://vitejs.dev/guide/features#glob-import