“切图仔”不会调用图片还叫什么切图仔?因此汇总vue3项目中常见6种图片资源引入方式,总有一种能解决你当下难题;其中包含借助vite-plugin-vue-images来实现自动导入图片,从而不影响大家“摸鱼”时间,正所谓多学一个知识就能少写一行代码
1 | <img src="@/assets/record.jpg" /> |
1 2 3 4 5 | # template <img :src="imgSrc" /> # js import imgSrc from '@/assets/painting.jpg'; |
1 | npm i vite-plugin-vue-images -D |
1 2 3 4 5 6 7 8 9 10 11 12 | # vite.config.ts import { defineConfig,loadEnv} from 'vite' import ViteImages from 'vite-plugin-vue-images' export default ({ mode }) => defineConfig({ plugins: [ ViteImages({ dirs: ['src/assets'], // 图像目录的相对路径 extensions: ['jpg', 'jpeg', 'png', 'svg', 'webp'], // 有效的图像扩展 customResolvers:[], // 覆盖名称->图像路径解析的默认行为 customSearchRegex: '([a-zA-Z0-9]+)', // 重写搜索要替换的变量的Regex。 }), ] |
自动导入图像,同级目录的文件名不能重复!命名遵循大驼峰命名方式
1 2 | // src/assets/straight_man.jpg <img :src="StraightMan" /> // 注意命名遵循大驼峰命名方式 |
1 2 3 4 5 6 7 8 9 | <template> <div> <img :src="straight_man" /> </div> </template> <script setup lang="ts"> import straight_man from '@/assets/straight_man.jpg' </script> |
1 2 3 4 5 6 7 8 | # template <img :src="getAssetsFile" /> # js function getAssetsImages(name) { return new URL(`/src/assets/${name}`, import.meta.url).href; } const getAssetsFile = getAssetsImages('valentine_day.jpg'); |
使用vite的import.meta.glob或import.meta.globEager,两者的区别是前者懒加载资源,后者直接引入;不推荐,这种方式使时候引入的文件必须指定到具体文件夹路径,传入的变量中只能为文件名,不能包含文件路径,可以采用方式四替代该方案
1 2 3 4 5 6 7 8 9 10 | # template <img :src="getAssetsHomeFile('time_shuttle.jpg')" /> # js let getAssetsHomeFile = (url: string) => { const path = `../assets/${url}`; const modules = import.meta.globEager('../assets/*'); console.log(modules[path]) return modules[path].default; }; |
1 2 | // src="" 一个斜杠就表示资源定位到public下 <img src="/images/effort.jpg" /> |
上一篇:Vite+Ts项目找不到模块“xxx”或其相应的类型声明
下一篇:没有了,已经是最新文章
支付宝扫一扫打赏
微信扫一扫打赏
共 0 条评论关于"Vite+Vue3图片资源六种引入方式,总有一种能解决你当下难题"
最新评论