In Vite, the require
function is not used. Instead, you should use the import
statement (Vite is the default module bundler for Nuxt 3.)
There are two problems:
- After the build, Nuxt will change the assets directory and the file names.
- Aliases do not convert to the absolute path when used dynamically.
So you can't even do this even:
<img :src="`_nuxt/assets/img/${imageName}`">
During development mode, it works, but not after the build.
Solution 1
You can import images and then use them like this:
<script lang="ts" setup>
//@ts-ignore
import image1 from "../assets/images/image1.jpg";
//@ts-ignore
import image2 from "../assets/images/image2.jpg";
//@ts-ignore
import image3 from "../assets/images/image3.jpg";
const images = [ image1, image2, image ]
</script>
Solution 2
I found this way:
<script>
const glob = import.meta.glob("~/assets/images/how-to-use/*", {
eager: true,
});
const getImageAbsolutePath = (imageName: string): string => {
return glob[`/assets/images/how-to-use/${imageName}`]["default"];
};
</script>
You can pass your imageName
(don't forget the extension) to this function and retrieve the absolute path.
This approach continues to function correctly even after the build.
Solution 3
you can put your images in the public
directory
learn more: https://nuxt.com/docs/getting-started/assets/#public-directory
The public/ directory content is served at the server root as-is.