vite+vue3中静态资源的几种引入方式

1,668 阅读1分钟

一、将资源引入为 URL

import loginImg from "../assets/images/denglu.png"
使用方式:
<img :src="loginImg" alt="" />

二、new URL(url, import.​meta.url)

import.​meta.url 是一个 ESM 的原生功能,会暴露当前模块的 URL。将它与原生的 URL 构造器 组合使用,在一个 JavaScript 模块中,通过相对路径我们就能得到一个被完整解析的静态资源 URL:

const loginImg = new URL('../assets/images/denglu.png', import.meta.url).href

使用方式同上

注意:网上看到有些是这样写的,并不可以,是错误写法
const loginImg = () => { return new URL('../assets/images/denglu.png', import.meta.url).href }

三、import.meta.globEager方法

import.meta.globEager 可以理解为vite中代替webpack的 require.context 自动导入文件

新建一个imgUtil.js文件

const getImgSrc = (name) => {
    if (typeof name === 'undefined') return 'error.png'
    const path = `/src/assets/images/${name}.png`
    const modules = import.meta.globEager('/src/assets/images/*')
    return modules[path]?.default
}

export default getImgSrc

在APP.vue中引入

import {provide} from 'vue'
import getImgSrc from '@/utils/imgUtil.js'
provide('getImgSrc', getImgSrc)

使用:

import { inject } from 'vue'
const getImgSrc = inject('getImgSrc')

模板中:
<img :src="getImgSrc('文件名')"  alt="">