我最近给一个 Vue CLI 项目做了图片优化。批量转换 166 张 PNG 后,这批图片的体积从 15.07 MB 降到 9.11 MB,缩小约 39.6%。同期,完整生产包从 137.69 MiB 降到 132.06 MiB,降幅约 4.1%。
同一次优化为什么会有两个降幅?因为前者只统计转换过的图片,后者还包括 JS、CSS、字体和第三方资源。至于用户打开网页能快多少,还要看浏览器在这个页面实际下载了哪些图片,以及它们是否影响首屏显示。
下面用一个可以直接运行的脚本,演示从批量转换到验证效果的过程。
一、先确定要转换哪些图片
可以从 Chrome DevTools → Network → Img 开始。勾选 Disable cache 后刷新页面,按大小排序,优先找体积较大、页面确实会请求的本地图片,例如首屏背景、活动横幅和装饰图。
查到图片后,再到项目中定位它的引用。Vue 项目里的图片可能写在 <img src>、JS 的 import 或 require()、CSS 的 url() 中。一个仓库如果包含多个前端应用,要先确认图片和引用属于哪个应用。
转换格式需要重新编码。 如果只把 banner.png 重命名为 banner.webp,文件内部仍然是 PNG 数据,体积也不会变化。
WebP 支持有损和无损压缩,也支持透明背景。下面用无损模式做第一轮迁移,只有图片确实变小、可见像素通过校验时,才生成新的 WebP 文件。
二、用 Sharp 批量转换
示例使用 Node.js 22 和 sharp@0.35.5。可以在前端项目旁边建一个独立的工具目录,把 Sharp 安装在那里。
mkdir image-tools
cd image-tools
npm init -y
npm install sharp@0.35.5
在 image-tools 下新建 png-to-webp.cjs。脚本可以接收多个图片文件或目录。默认只预览,添加 --write 后才保存文件。
const fs = require('node:fs/promises')
const path = require('node:path')
const sharp = require('sharp')
const args = process.argv.slice(2)
const write = args.includes('--write')
const inputs = args.filter(arg => arg !== '--write')
async function* findPngs(input) {
const stat = await fs.lstat(input)
if (stat.isDirectory()) {
for (const name of await fs.readdir(input)) {
yield* findPngs(path.join(input, name))
}
} else if (stat.isFile() && /\.png$/i.test(input)) {
yield input
}
}
function isAnimatedPng(bytes) {
for (let offset = 8; offset + 12 <= bytes.length;) {
const chunkType = bytes.toString('ascii', offset + 4, offset + 8)
if (chunkType === 'acTL') return true
if (chunkType === 'IEND') return false
offset += bytes.readUInt32BE(offset) + 12
}
return false
}
function rgba(bytes) {
return sharp(bytes).toColourspace('srgb').ensureAlpha().raw().toBuffer()
}
async function sameVisiblePixels(input, output) {
const [before, after] = await Promise.all([rgba(input), rgba(output)])
if (before.length !== after.length) return false
for (let i = 0; i < before.length; i += 4) {
const alpha = before[i + 3]
if (alpha !== after[i + 3]) return false
if (alpha !== 0 && !before.subarray(i, i + 3).equals(after.subarray(i, i + 3))) {
return false
}
}
return true
}
async function convert(file) {
const input = await fs.readFile(file)
const meta = await sharp(input).metadata()
if (meta.format !== 'png') {
console.log('跳过,文件实际格式为 ' + meta.format, file)
return
}
if (meta.width > 16383 || meta.height > 16383 ||
meta.depth !== 'uchar' || meta.orientation > 1 || isAnimatedPng(input)) {
console.log('跳过,尺寸、位深、方向或动画需要单独处理', file)
return
}
const encoder = sharp(input)
if (meta.hasProfile) encoder.withIccProfile('srgb')
const webp = await encoder.webp({ lossless: true, effort: 4 }).toBuffer()
if (webp.length >= input.length) {
console.log('保留 PNG,转换后未变小', file)
return
}
const result = await sharp(webp).metadata()
if (result.format !== 'webp' || result.width !== meta.width ||
result.height !== meta.height || !(await sameVisiblePixels(input, webp))) {
throw new Error('WebP 格式、尺寸或可见像素校验失败')
}
const output = file.replace(/\.png$/i, '.webp')
if (write) {
try {
await fs.writeFile(output, webp, { flag: 'wx' })
} catch (error) {
if (error.code !== 'EEXIST') throw error
console.log('跳过,已有同名 WebP', output)
return
}
}
const saved = ((1 - webp.length / input.length) * 100).toFixed(1)
console.log(write ? '已生成' : '预览', file, '→', output, '减少 ' + saved + '%')
}
async function main() {
if (!inputs.length) {
throw new Error('用法:node png-to-webp.cjs [--write] <PNG 文件或目录>')
}
for (const input of inputs) {
for await (const file of findPngs(input)) {
try {
await convert(file)
} catch (error) {
console.error('处理失败', file, error.message)
process.exitCode = 1
}
}
}
}
main().catch(error => {
console.error(error.message)
process.exitCode = 1
})
假设前端项目叫 my-vue-app,并且与 image-tools 同级,可以先对首页图片目录预览一次。
# 预览转换结果
node ./png-to-webp.cjs "../my-vue-app/src/assets/images/home"
# 确认范围后实际写入
node ./png-to-webp.cjs "../my-vue-app/src/assets/images/home" --write
脚本会把新的 .webp 保存到原图旁边,保留原 PNG。`flag: 'wx'` 用于保护已有的同名文件。项目里遇到同名 WebP 时,我先检查了画面,再用新的文件名保存通过校验的版本。
批量处理还容易遇到两种特殊情况。一是文件名虽然以 .png 结尾,实际内容却是 JPEG,所以要读取真实格式。二是 WebP 单边最多为 16,383 像素,超宽图需要先根据页面展示需求决定是否缩放。
三、改引用时,按具体图片替换
生成 .webp 后,浏览器还要通过新的路径才能用上它。例如,假设下面的代码位于 src/views/Home.vue:
<template>
<section class="hero">
<img src="../assets/images/person.webp" alt="首页人物插图" />
</section>
</template>
<style scoped>
.hero {
background-image: url('../assets/images/banner.webp');
}
</style>
项目较大时,可以用脚本输出的 原 PNG 路径 → 新 WebP 路径 建立清单,再逐条更新 Vue、JS 和 CSS 中能定位到具体文件的引用。代码中的远程 URL、接口返回值和动态拼接路径,应单独核查。全仓搜索并替换 .png 很容易误改这些地址。
如果项目使用 Vue CLI 和 Webpack,留在 src/assets 中、未被依赖或批量导入的原 PNG,通常不会进入 dist。`public` 中的资源通常会原样复制,二者的构建规则不同。
提交代码时,把新图片和引用改动放进同一个 Git 提交。 我遇到过一次本地打包成功、服务器却连续报 Can't resolve '*.webp' 的情况。原因是本地磁盘上有图片,但提交里只有改过路径的代码。提交前看一眼 git status --short,`??` 表示文件还未被 Git 跟踪。
四、用构建结果和浏览器验证收益
一批图片处理完后,按项目 package.json 中的命令执行生产构建,例如 npm run build 或 npm run build:prod。然后分别看三组数据:
| 想确认什么 | 在哪里看 |
|---|---|
| 转换的图片缩小了多少 | 比较原 PNG 与 WebP 的文件大小 |
| 生产包缩小了多少 | 对比前后两次构建的完整 dist 目录 |
| 用户打开页面快了多少 | 用 Network 对比实际下载量,用 Lighthouse 或 Performance 查看 LCP 等指标 |
Lighthouse 总分可能变化不大。 在我的测试中,首页首次访问的图片下载量从 7.05 MB 降到 5.84 MB,但 LCP(首屏最大内容出现的时间)只从 3.30 秒变为 3.28 秒。首页的 LCP 元素是已经提前优化过的背景图,批量转换主要省下了其他图片的流量。
赛事搜索页则更明显。该页的 LCP 元素正是一张大背景图,单独将它从 7.01 MiB 压到 1.96 MiB 后,在本地冷缓存、模拟 20 Mbps 网络的相同条件下,LCP 中位数从 10.93 秒降到 4.60 秒。
所以,选图时可以先看两件事:这张图有多大,以及它在什么时候影响用户看到页面。 优先处理首屏的大图,比单纯追求转换数量更容易改善用户实际感受到的加载速度。
935




被折叠的 条评论
为什么被折叠?



