0


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

一、前言

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

二、实现

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

yarn add imagemin imagemin-webp

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

// vite.config.tsimport imagemin from'imagemin';import imageminWebp from'imagemin-webp';import path from'path';import{ readdirSync, lstatSync, unlinkSync }from'fs';exportdefaultdefineConfig({
    plugins:[vue(),{
          name:'webp-converter',
          apply:'build',asyncgenerateBundle(){// 需修改:存储图片的文件夹相对于项目根目录的路径const imgDirPath ='img';// 读取文件夹const files =readdirSync(imgDirPath);// 筛选出需要处理的图片const images = files.filter(file=>{const filePath = path.join(imgDirPath, file);returnlstatSync(filePath).isFile()&&/\.(jpg|jpeg|png)$/i.test(file);});// 考虑到计算机运存,设置最大并发处理数量,递归执行,否则可能会打包失败const maxConcurrent =5;let index =0;constprocessNext=async()=>{if(index >= images.length)return;const image = images[index++];const inputFilePath = path.join(imgDirPath, image);try{awaitimagemin([inputFilePath],{
                  destination: imgDirPath,
                  plugins:[imageminWebp({
                      quality:75// 设置输出的 WebP 质量})]});// 看需求是否要删除原始图片// unlinkSync(inputFilePath);}catch(error){
                console.error(`Error processing ${inputFilePath}:`, error);}awaitprocessNext();};const tasks = Array.from({ length: maxConcurrent }, processNext);await Promise.all(tasks);},}],// ...})

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

安装懒加载依赖
yarn add vue-lazyload
配置指令
// main.tsimport{ createApp }from'vue'import App from'./App.vue'import VueLazyload from'vue-lazyload'// 懒加载的默认图import lazy_img from'./assets/lazy.jpg'const app =createApp(App)
app.use(VueLazyload,{ 
    loading: lazy_img,
    filter:{// 过滤器,可以对图片进行一些处理webp(listener, options){if(options.supportWebp &&/\.(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格式图片的工具方法,在使用静态图片时使用

当不能使用vueLazyload的情况下,可以使用以下方法替换图片原路径为webp格式路径

// utils/common.ts// 判断当前环境是否支持webp,该方法是从vueLazyload中找到的,如果有更好的办法可告知functionsupportWebp(){let support: boolean =true

    type TkTestImages ={
        lossy: string;
        lossless: string;
        alpha: string;
        animation: string;}functioncheckWebpFeature(feature: keyof TkTestImages, callback: Function){const kTestImages: TkTestImages ={
            lossy:'UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA',
            lossless:'UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==',
            alpha:'UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==',
            animation:'UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA'}const img =newImage()
        img.onload=function(){const result =(img.width >0)&&(img.height >0)callback(result)}
        img.onerror=function(){callback(false)}
        img.src ='data:image/webp;base64,'+ kTestImages[feature]}checkWebpFeature('lossy',(isSupported: boolean)=>{ support = isSupported })checkWebpFeature('lossless',(isSupported: boolean)=>{ support = isSupported })checkWebpFeature('alpha',(isSupported: boolean)=>{ support = isSupported })checkWebpFeature('animation',(isSupported: boolean)=>{ support = isSupported })return support
}exportfunctionloadWebpImg(src: string){if(/\.(png|jpe?g)$/.test(src)){let link = src
        if(supportWebp()&&/\.(png|jpe?g)$/.test(link)){
            link = link.replace(/\.\w+$/,'.webp');}return link
    }return src
}
<img :src="loadWebpImg(imgPath)":alt="itemName"/>
标签: vue.js javascript css

本文转载自: https://blog.csdn.net/weixin_45729375/article/details/140793884
版权归原作者 SicaWang 所有, 如有侵权,请联系我们删除。

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

还没有评论