Vite 动态资源导入

3,119 阅读1分钟

由于require方法数属于Webpack的方法在Vite项目中无法使用

报错:require is not defind

方式一(适用于引用单个资源)

<img :src="homeBg" />
import homeBg from 'src/assets/images/home/home_bg.png

方式二(动态传入文件路径与动态绑定)

utils.js 中定义 getAssetsFile 方法

// 获取assets静态资源
export const getAssetsFile = (url: string) => {
  return new URL(`../assets/images/${url}`, import.meta.url).href;
};

使用方式:

// 图片引用
<img :src="getAssetsFile('图片名.png')">

// 动态绑定背景图
<div :style="{'background-image': 'url(' + getAssetsFile(`${bgSrc}.png`) + ')'}"></div>

第三种方式(适用于多个资源文件,这种方式引入的文件必须指定到具体文件夹路径,传入的变量中只能为文件名,不能包含文件路径)

// 获取assets静态资源
const getAssetsFile = (url: string) => {
  const path = `../assets/images/home/${url}`;
  const modules = import.meta.glob("../assets/images/home/*");
  return modules[path].default;
};

export default {
  getAssetsFile,
};

// js 导入
import util from 'src/util/utils'

// html 使用
<img :src="getAssetsFile('图片名.png')">  -> 只能使用文件名不能包含路径

踩坑:Vite项目中 CSS使用背景图片的时候需使用相对路径,使用绝对路径后打包的时候会报错 T_T

参考文章: blog.csdn.net/weixin_4374…