vue3+vite实现静态站图片资源的压缩和格式转换(webp)

一、前言

最近做了几个静态站,图片资源是放在项目中打包出来的,而在通过google网站测试时在图片大小方面拉低了网站分数并建议使用更适合html5的webp格式,因此本文将介绍静态站如何压缩图片大小并改变图片格式为webp。

二、实现

1、下载转换图片格式的依赖

yarn add imagemin imagemin-webp

2、vite配置,打包时对图片格式进行修改和压缩

// vite.config.ts
import imagemin from 'imagemin';
import imageminWebp from 'imagemin-webp';
import path from 'path';
import { readdirSync, lstatSync, unlinkSync } from 'fs';

export default defineConfig({
	plugins: [
	    vue(),
	    {
	      name: 'webp-converter',
	      apply: 'build',
	      async generateBundle() {
	      	// 需修改:存储图片的文件夹相对于项目根目录的路径
	        const imgDirPath = 'img'; 
	        // 读取文件夹
	        const files = readdirSync(imgDirPath);
	        // 筛选出需要处理的图片
	        const images = files.filter(file => {
	          const filePath = path.join(imgDirPath, file);
	          return lstatSync(filePath).isFile() && /\.(jpg|jpeg|png)$/i.test(file);
	        });
	
			// 考虑到计算机运存,设置最大并发处理数量,递归执行,否则可能会打包失败
	        const maxConcurrent = 5; 
	        let index = 0;

	        const processNext = async () => {
	          if (index >= images.length) return;
	
	          const image = images[index++];
	          const inputFilePath = path.join(imgDirPath, image);
	
	          try {
	          	await imagemin([inputFilePath], {
	              destination: imgDirPath,
	              plugins: [
	                imageminWebp({
	                  quality: 75 // 设置输出的 WebP 质量
	                })
	              ]
	            });
	            // 看需求是否要删除原始图片
	            // unlinkSync(inputFilePath);
	          } catch (error) {
	            console.error(`Error processing ${inputFilePath}:`, error);
	          }
	          await processNext();
	        };
	
	        const tasks = Array.from({ length: maxConcurrent }, processNext);
	        await Promise.all(tasks);
	      },
	    }
	],
  	// ...
})

3、懒加载配置(如果项目读取图片使用的懒加载)

安装懒加载依赖
yarn add vue-lazyload
配置指令
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import VueLazyload from 'vue-lazyload'
// 懒加载的默认图
import lazy_img from './assets/lazy.jpg'

// 判断浏览器是否支持 webp
const isWebpSupported = !![].map && document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0;

const app = createApp(App)
app.use(VueLazyload, { 
	loading: lazy_img,
    filter: {
    	webp(listener) {
        	if (isWebpSupported) {
            	// 仅对路径以 'img/' 开头且是 png、jpg、jpeg 格式的图片进行webp转换
                if (/\.(png|jpe?g)$/.test(listener.src)) {
                	listener.src = listener.src.replace(/\.\w+$/, '.webp');
                }
            }
        }
    }
})
// ...
app.mount('#app')
<img v-lazy="imgPath" :alt="imgName">

4、对于非懒加载的图片(例如logo)

手动实现一个获取webp格式图片的工具方法,在使用静态图片时使用
// utils/common.ts
export function loadWebpImg(src:string):string{
    if (/\.(png|jpe?g)$/.test(src)) {
        let link = src
        const isWebpSupported = !![].map && document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0;
        if (isWebpSupported) {
            // 仅对路径以 'img/' 开头且是 png、jpg、jpeg 格式的图片进行webp转换
            if (/\.(png|jpe?g)$/.test(link)) {
                link = link.replace(/\.\w+$/, '.webp');
            }
        }
        return link
    }
    return src
}
<img :src="loadWebpImg(imgPath)" :alt="itemName" />
  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue3、Vite 和 TypeScript 的组合通常用于构建高性能的现代Web应用。对于静态图片处理,你可以采用以下步骤: 1. **安装依赖**: - 使用`npm`或`yarn`安装`vue.config.js`文件,以便配置Vite支持TypeScript:`npm install @vitejs/plugin-vue@next typescript` - 如果需要处理图片,安装一个图片处理库,如`sharp`(Node.js的高性能图像处理库),但在客户端运行Vite时,可能不会直接引入,因为Vite默认会打包到浏览器。 2. **配置Vite**: - 在`.viteignore`文件中忽略`node_modules`,防止打包过多不必要的体积。 - 更新`vite.config.ts`,添加TypeScript支持,配置Vite插件: ```typescript import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; export default defineConfig({ plugins: [vue()], build: { target: 'esnext', tsconfig: './tsconfig.build.json', // 根据项目需求配置正确的TS编译配置 }, }); ``` 3. **图片资源管理**: - 将图片放入`public`目录下,Vite会自动处理静态资产。 - 对于动态生成的图片(例如需要根据某些条件调整大小或添加水印),可以使用JavaScript (ES6+) 动态创建Image对象,或者在服务器端渲染时使用像`sharp`这样的库处理图片后再返回给前端。 4. **使用TypeScript**: - 引入图片处理模块时,确保正确导入并处理类型安全: ```typescript import sharp from 'sharp'; // 假设sharp是全局可用的,若不在Node环境则需引入库 async function resizeImage(src: string): Promise<Buffer> { const resized = await sharp(src) .resize(300, 200) // 设置新尺寸 .toBuffer(); // 转换为Buffer对象 return resized; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SicaWang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值