新博客重构需要对上传的图片做转换到webp压缩体积,
找到个处理库sharp,官网
- 安装
直接npm install sharp 即可,需要注意的是,对环境有依赖的,加上参数安装
npm install --include=optional sharp
以避免类似情况
- 转换
import sharp from "sharp";
await sharp(array, {failOnError: false, animated: true})
.webp()
.toFile(`xxxx.webp`)
其中,第一个参数,可以是多种类型
animated: true 可以指出gif 转 webp
转换可能会报错,类似情况
VipsJpeg: Premature end of JPEG file Error message
参数failOnError: false可以解决,也可以具体处理报错: