如何压缩?
解读
面试官抛出“如何压缩?”这一看似简短的问题,通常不是让你背诵某段配置,而是考察三层能力:
- 是否真正理解 Gulp 的流式思想(pipe、Vinyl、Transform Stream);
- 能否针对国内真实业务场景(Webpack 并存、CDN 上传、CI 集成、合规审计)给出可落地的工程化方案;
- 是否具备性能与可维护性兼顾的意识(缓存、增量、并行、差分更新)。
回答时务必先讲思路再亮代码,并主动把“压缩”拆成“JS / CSS / HTML / 图片 / 字体”五类资源,分别给出插件选型、参数调优、坑点规避、产物验证四步闭环,体现资深前端工程师的系统性。
知识点
- 流式管道:Gulp 的 src → pipe → dest 本质是 Node Transform Stream,插件必须返回 Stream 且支持 flush。
- 国内镜像:gulp-uglify 依赖的 terser 在 CI 中常因 npm 源超时,需显式切换淘宝源或pnpm 缓存。
- 双目标产物:国内项目普遍要求同时输出 sourcemap 与 .min 文件,以便 Sentry 错误回溯与合规审计。
- 图片压缩:gulp-imagemin 在 macOS M1/Win 下需手动安装 optipng-bin 与 mozjpeg 的国内预编译镜像,否则必现 postinstall 404。
- 增量与缓存:gulp-newer 与 gulp-cache 组合可把 10 s 的压缩任务降到 1 s,是面试加分项。
- 并行安全:gulp-parallel 对文件系统锁敏感,必须保证 dest 目录隔离,否则 CI 并发会随机失败。
- 产物校验:压缩后需自动计算 gzip 体积与 brotli 体积并写入 manifest.json,方便运维在 Nginx 侧开启对应算法。
- 法规合规:国内金融、政务项目要求保留原始注释中的许可证头(@license),uglify 需配置 output.comments 正则保留。
答案
“压缩”在 Gulp 里本质是基于 Transform Stream 的资源转换流水线。我把它拆成五步闭环:选型、参数、优化、验证、集成。以下用最新国内可落地配置举例,可直接用于生产。
-
JS 压缩
插件选型:terser 而非 uglify-es,因为 terser 对 ES2022 语法支持更好,且国内镜像源同步及时。
核心代码:import { src, dest, parallel } from 'gulp'; import terser from 'gulp-terser'; import sourcemaps from 'gulp-sourcemaps'; import rename from 'gulp-rename'; import header from 'gulp-header'; import { readFileSync } from 'fs'; const pkg = JSON.parse(readFileSync('./package.json')); const banner = `/*! ${pkg.name} v${pkg.version} | ${pkg.license} */${'\n'}`; export function jsMinify() { return src('dist/js/*.js', { sourcemaps: true }) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(terser({ compress: { drop_console: true, // 生产环境去掉 console drop_debugger: true, pure_funcs: ['console.log'] // 合规审计常用 }, mangle: { safari10: true }, // 解决国内低版本 Safari 10 白屏 format: { comments: /^!/ } // 保留 banner })) .pipe(header(banner)) // 重新打上许可证头 .pipe(rename({ suffix: '.min' })) .pipe(sourcemaps.write('.', { includeContent: false, sourceRoot: '../src' })) .pipe(dest('dist/js')); } -
CSS 压缩
插件选型:gulp-csso + gulp-postcss(autoprefixer),csso 比 clean-css 在国内测试里多节省 3 % 体积。
关键参数:import csso from 'gulp-csso'; import postcss from 'gulp-postcss'; import autoprefixer from 'autoprefixer'; export function cssMinify() { return src('dist/css/*.css') .pipe(postcss([autoprefixer({ overrideBrowserslist: ['> 1%', 'ie >= 10'] })])) .pipe(csso({ restructure: true, sourceMap: true })) .pipe(rename({ suffix: '.min' })) .pipe(dest('dist/css')); } -
HTML 压缩
国内项目常忽略,实际可省 15 % 体积。import htmlmin from 'gulp-htmlmin'; export function htmlMinify() { return src('dist/**/*.html') .pipe(htmlmin({ collapseWhitespace: true, removeComments: true, minifyJS: { compress: { drop_console: true } }, minifyCSS: true, // 保留微信 JSSDK 的 config 模板语法 ignoreCustomFragments: [/<%[\s\S]*?%>/] })) .pipe(dest('dist')); } -
图片压缩
解决国内 CI 404 的终极方案:提前把 mozjpeg、optipng、pngquant 的二进制放到公司私有 Nexus,然后在 .npmrc 里配optipng_binary_site=https://nexus.xxx.com/repository/node-binaries/代码:
import imagemin from 'gulp-imagemin'; import mozjpeg from 'imagemin-mozjpeg'; import pngquant from 'imagemin-pngquant'; export function imgMinify() { return src('src/img/**/*.{jpg,png}') .pipe(imagemin([ mozjpeg({ quality: 80, progressive: true }), pngquant({ speed: 1, quality: [0.8, 0.9] }) ], { verbose: true })) .pipe(dest('dist/img')); } -
并行与缓存
使用 gulp-newer 做增量,gulp-cache 做跨构建缓存,CI 里缓存目录挂到 ~/.gulp-cache。import cache from 'gulp-cache'; import newer from 'gulp-newer'; export function imgMinifyCached() { return src('src/img/**/*') .pipe(newer('dist/img')) .pipe(cache(imagemin(...), { name: 'img' })) .pipe(dest('dist/img')); } -
产物验证
压缩后自动计算 gzip 与 brotli 体积,写入 dist/manifest.json,供运维在 Nginx 侧开启对应算法。import { sync as gzipSync } from 'gzip-size'; import { brotliCompressSync } from 'zlib'; import { writeFileSync } from 'fs'; function genManifest() { const files = glob.sync('dist/**/*.{js,css}'); const map = {}; files.forEach(f => { const source = readFileSync(f); map[f] = { raw: source.length, gzip: gzipSync(source), br: brotliCompressSync(source).length }; }); writeFileSync('dist/manifest.json', JSON.stringify(map, null, 2)); } export const build = parallel(jsMinify, cssMinify, htmlMinify, imgMinifyCached, genManifest);
通过以上六步,既保证体积最优,又兼顾 CI 速度、合规审计与运维可观测性,是国内一线厂的标准答案。
拓展思考
- 若公司同时用 Webpack 与 Gulp,可把 Gulp 定位为“后处理压缩网关”:Webpack 负责 bundle 与拆包,Gulp 负责二次压缩、添加水印、上传 CDN、回源预热,实现双工具链互补。
- 对微前端基座场景,主应用与 10 + 子应用共用 CDN,需在 Gulp 里做差分压缩:先计算线上旧文件的 hash,仅对 diff 部分重新压缩,可把 5 min 的全量任务降到 20 s。
- WebP / AVIF 国内落地仍受微信内置浏览器限制,可在 Gulp 里并行生成 WebP 与原始 PNG/JPG,并在 HTML 压缩阶段自动注入
<picture>标签与type="image/webp",实现渐进式升级。 - 若面试继续追问“如何验证压缩后功能无损?”,可答:
- 对 JS 用 terser 的 --mangle-props 白名单结合 Jest 单元测试做属性名快照比对;
- 对 CSS 用 pixelmatch 截图对比(Puppeteer 驱动),确保 csso 重组后无 1 px 偏差;
- 对图片用 SSIM 结构相似度 > 0.98 作为门禁,低于阈值自动回滚。
这套无损验证体系是高级前端与 QA 协同的标杆实践,可让面试官直接拍板通过。