返回博客

Vite 动态引入图片

本文介绍了使用 Vite 动态引入图片的几种方法,包括使用 `import.meta.globEager`、`import()` 和 `new URL()` 等方式,并对各种方法进行了比较和优化。

Mt.r
|

官方文档

搜集的代码

<img :src="getSrc('Contact_us')" alt="" />
// 动态获取图片
const getImage = (name: string) => {
  const path = `../../common/assets/Car/${name}.png`;
  const modules = import.meta.globEager('../../common/assets/Car/*.png');
  return modules[path].default;
};
const imgUrl = reactive<object[]>([])
const getImage = () => {
  mapElements.map((item) => {
    const obj: { img: string, select: string} = {
      img: '',
      select: ''
    }
    import('./image' + item.path).then((res) => {
      obj.img = res.default
    })
    imgUrl.push(obj)
  })
}
function getImageUrl(name) {
  return new URL(`../assets/blogPhotos/${name}.jpg`, import.meta.url).href;
}
require('./profilePic/profile_pic_01.png')
// 等价于
new URL('./profilePic/profile_pic_01.png', import.meta.url).href

相关文章

-vue3 vite 怎么动态引用图片