前端图片压缩

当代码打包完毕后,应该执行图片压缩、js上传cdn、图片上传cdn操作。
现在来实现上传图片前的图片压缩

当图片压缩后上传cdn服务器时
注意:需要修改output.publicPath 为cdn路径
如:

   output: {
       path: path.resolve(__dirname, '../dist'),
       filename: "js/[name].js",
       publicPath: publicPath
   },

如果有使用worker-loader 一定同步 woker-loader配置项publicPath

   {
       test: /\.worker\.js$/,
       loader: "worker-loader",
       options: {
           publicPath: publicPath,
       },
   },

现在来实现图片压缩

一、使用在线网站方式

在线图片压缩tinypng

二、使用代码实现

方式一:npm库 tinypng-cli
代码实现之前需要https://tinypng.com/注册 获取app-key
前端图片压缩_第1张图片
package.json 新增 tinyPng命令

  "scripts": {
    "commit": "cz",
    "tinyPng" : "tinypng assets/ -k b5hYk5TCn2snv3J4v9xW9MFvDngtMj1F"
  },

前端图片压缩_第2张图片
方式二:使用imagemin实现

assetsBuild.js

import {  compressImage } from "./compress.js"
import {globby} from 'globby';
import path from "node:path"
import fs from 'fs-extra'
import { isNotJunk } from 'junk';
import chalk from 'chalk';

/**
 * 获取目标文件夹中可以压缩的文件
 * @returns Array of paths to files
 */
async function getImages(output='dist/images/') {
    return  (await globby(path.resolve(process.cwd(),output),{
        expandDirectories: {
            extensions: ['jpg',"png","jpeg"]
        }
    })).filter(isNotJunk)
}



export default async function assets(options) {
    const {input,output,type="builtin"} = options ?? {}
    // 移动图片文件夹到打包路径
    fs.copySync(path.resolve(process.cwd(),input?input:"src/assets/"),path.resolve(process.cwd(),output?output:"dist/images/"));
    // 获取图片路径
    const files = await getImages(output)
    files.forEach(async(file)=>{
        const buffer = fs.readFileSync(file)
        const result= await compressImage(buffer,type)
        if (result) {
            const radio = ((1 - result.byteLength / buffer.byteLength) * 100).toFixed(2);
            fs.writeFileSync(file.trim(), result);
            console.log(chalk.green("压缩图片成功:" + file.trim(),`,压缩率:${radio}%`));
        }
    })
}

compress.js

import imagemin from "imagemin";
import imageminJpegtran from "imagemin-jpegtran-cn"
import imageminPngquant from "imagemin-pngquant-cn"
import tinify from "tinify";
tinify.key = "BJJt8s2Q4cL0B5cgD7PnxM12XPyyZjmD";

const COMPRESS_TYPE = {
	builtin: 'builtin',
	tinypng: 'tinypng',
}

export function compressImage(buffer, type = "builtin") {
	if (!COMPRESS_TYPE[type]) {
		type = COMPRESS_TYPE.builtin;
	}
	switch (type) {
		case COMPRESS_TYPE.builtin:
			return imagemin.buffer(buffer, {
				plugins: [
					imageminJpegtran(),
					imageminPngquant({
						quality: [0.6, 0.8]
					})
				]
			});
		case COMPRESS_TYPE.tinypng:
			console.log("tinypng")
			return new Promise(r=>{
				tinify.fromBuffer(buffer).toBuffer(function(err, resultData) {
					if (err) throw err;
					r(resultData)
				});
			})
	}
}

你可能感兴趣的:(前端,javascript,vue.js)