CI 上的 4 分 28 秒
每次提交后要等 4 分半才能看到效果,本地是 47 秒。改一个小功能的时间,前三分之一花在等构建上。
对比数据:
| 环境 | 首次 | 二次(缓存) |
|---|---|---|
| 本地 | 2 分 12 秒 | 47 秒 |
| CI | 4 分 28 秒 | 3 分 51 秒 |
本地二次 47 秒说明 Webpack 的 persistent cache 已经生效了。CI 每次都是全新容器,缓存丢失,退化到全量构建。
第一步:找到真正的瓶颈
盲目优化之前先测量。构建各阶段耗时:
// webpack.config.js
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'json',
generateStatsFile: true,
statsFilename: './stats.json',
}),
],
stats: { children: true, timings: true },
profile: true,
};
看 Stats 的 breakdown:
Hash: 12.3s
Modules: 86.4s ← 最多:模块构建
Chunk: 4.1s
Seal: 38.7s ← 优化阶段(压缩、Tree Shaking)
Emit: 18.2s ← 输出文件
Total: 158.7s
结论:Modules + Seal 占 79%。前者是 babel/ts-loader 转换,后者是 Terser 压缩和 CSS 优化。
再看模块数量:
Total modules: 8,432
node_modules: 7,891 (93.6%) ← 绝大部分是第三方依赖
src/: 541 (6.4%)
93.6% 的模块来自 node_modules,而这些文件每次构建都不会变。
第二步:依赖预编译
这是收益最大的一项。
// webpack.config.js(Vue CLI / Vue2 项目)
module.exports = {
configureWebpack: {
module: {
rules: [
{
test: /\.m?js$/,
include: /node_modules/, // ❌ 依赖不走 babel
exclude: /node_modules\/(?!(element-ui)/)/,
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: { cacheDirectory: true }, // Vue Loader 缓存
},
],
},
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename],
},
},
},
};
cacheDirectory: true 让 vue-loader 把编译结果缓存到 node_modules/.cache,跳过未变更组件的重新编译。
实测:
优化前:158.7s
+ 依赖预编译:96.2s (-39%)
第三步:换 esbuild/terser 压缩
Terser 是最慢的一环,换成 esbuild:
// webpack 5 自带 esbuild 插件
const ESBuildMinifyPlugin = require('esbuild-webpack-plugin');
module.exports = {
optimization: {
minimize: true,
minimizer: [
new ESBuildMinifyPlugin({
target: 'es2018',
css: true, // 一并处理 CSS 压缩
}),
// 保留 Terser 作为回退(esbuild 处理不了的语法)
new TerserPlugin({
parallel: true, // 关键:并行压缩
terserOptions: { compress: { drop_console: true } },
}),
],
splitChunks: {
chunks: 'all',
cacheGroups: {
// 把变化频率低的依赖单独打包,提高缓存复用率
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
priority: -10,
chunks: 'initial',
},
common: {
minChunks: 2,
priority: -20,
chunks: 'initial',
reuseExistingChunk: true,
},
},
},
},
};
splitChunks 的拆分策略很关键:
优化前:单一大包 3.2MB,任何改动都要重新构建全部
优化后:
vendors.js 2.1MB 依赖,缓存友好(很少变)
common.js 0.6MB 公共组件
app.js 0.5MB 业务代码(每次都变)
page-*.js 按路由拆分
打包不是目的。目的是让不常变的部分能被缓存,这样增量构建才有意义。
optimization: {
runtimeChunk: 'single', // 运行时单独打包,避免主代码改动导致 hash 全变
moduleIds: 'deterministic', // 稳定 ID,减少无意义的内容变化
},
实测:
优化前:96.2s
+ esbuild + splitChunks:51.3s (再 -47%)
第四步:Node 内存配置
构建 OOM 是常见问题,报错还很难懂:
FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
# .npmrc 或 CI 配置
NODE_OPTIONS=--max-old-space-size=4096
# 或 package.json
{
"scripts": {
"build": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vue-cli-service build"
}
}
注意 –max-old-space-size 设置过大反而更危险 —— 容器内存不够时会触发 OOM Killer,此时 Node 进程没有机会输出错误信息。设置为容器内存的 75% 左右比较稳妥。
CI 里配置:
# .gitlab-ci.yml
build:
stage: build
script:
- export NODE_OPTIONS="--max-old-space-size=3072"
- npm ci --prefer-offline --no-audit
- npm run build
resources:
limits:
memory: 4G
cpus: '4'
第五步:Docker 构建加速
CI 每次拉依赖、装 node_modules,是巨大浪费。
# ❌ 慢:每次都重新下载全部依赖
FROM node:20
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
# ✅ 快:分层缓存,只有 package.json 变了才重装依赖
FROM node:20-alpine AS builder
WORKDIR /app
# 先只拷贝依赖清单
COPY package*.json ./
RUN npm ci --prefer-offline --no-audit
# 再拷贝源码
COPY . .
RUN npm run build
# 运行阶段:不需要 node_modules
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
Docker BuildKit 缓存挂载
# syntax=docker/dockerfile:1
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
# 挂载 npm 缓存目录,构建时的下载结果可复用
RUN --mount=type=cache,target=/root/.npm \
npm ci --prefer-offline --no-audit
COPY . .
RUN --mount=type=cache,target=/root/.npm \
npm run build
BuildKit 加速拉取
docker buildx create --use --name builder
docker buildx build \
--platform linux/amd64 \
--cache-from type=registry,ref=app:buildcache \
--cache-to type=registry,ref=app:buildcache,mode=max \
--build-arg BUILDKIT_INLINE_CACHE=1 \
-t registry.example.com/app:latest \
--push .
实测:依赖安装从 42 秒降到 6 秒(缓存命中)。
迁移到 Vite
前五步做完,CI 还是 51 秒。继续优化的空间有限,于是评估迁移 Vite。
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { visualizer } from 'rollup-plugin-visualizer'
export default defineConfig({
plugins: [
vue(),
// 依赖预构建:把 CJS 依赖转成 ESM
optimizeDeps: {
include: ['vue', 'vue-router', 'pinia', 'element-plus'],
esbuildOptions: { target: 'es2015' },
},
visualizer({ open: false, filename: 'stats.html' }),
],
build: {
target: 'es2015',
// esbuild 压缩,比 terser 快一个数量级
minify: 'esbuild',
cssMinify: true,
reportCompressedSize: false, // 关闭 gzip 大小统计,提速
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
if (id.includes('element-plus')) return 'element-plus'
if (id.includes('echarts')) return 'echarts'
return 'vendor'
}
},
},
},
chunkSizeWarningLimit: 800,
},
server: {
port: 8888,
proxy: { '/api': { target: 'http://127.0.0.1:5005', changeOrigin: true } },
},
})
对比
| 指标 | Webpack 4 | Webpack 5 优化后 | Vite |
|---|---|---|---|
| 开发服务器启动 | 52s | 38s | 1.2s |
| 首次页面加载 | 12s | 9s | 1.8s |
| HMR | 3-8s | 2-4s | < 300ms |
| 生产构建 | 158s | 51s | 22s |
| 产物体积 | 3.2MB | 2.6MB | 2.4MB |
开发体验的提升比构建速度更重要 —— HMR 从秒级到亚秒级,改代码不用等。
需要注意的坑
// 1. CommonJS 依赖需要预构建
optimizeDeps: {
include: [
// 明确列出大体积 CJS 依赖,否则会逐个按需发现导致启动慢
'element-plus', 'lodash-es', 'dayjs', 'echarts',
],
}
// 2. 别名和静态资源处理
resolve: {
alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) },
extensions: ['.mjs', '.js', '.ts', '.jsx', '.json', '.vue'],
},
// 3. 环境变量要写 VITE_ 前缀才会暴露给前端
// .env.production
VITE_API_BASE=/api
// 4. 生产环境关掉 sourcemap
build: { sourcemap: false }
CI 缓存完整配置
最终 GitLab CI 配置:
stages: [install, test, build]
variables:
NODE_OPTIONS: "--max-old-space-size=3072"
npm_config_registry: "https://registry.npmmirror.com"
cache:
key:
files: [package-lock.json]
prefix: "npm"
paths:
- node_modules/
- .npm/
install:
stage: install
script:
- npm ci --prefer-offline --no-audit
cache:
key: "npm-$CI_COMMIT_REF_SLUG"
paths: [node_modules/, .npm/]
policy: pull-push
test:
stage: test
script:
- npm run lint
- npm run test:unit -- --coverage
coverage: '/coverage\/.*\.html$/'
build:
stage: build
script:
- npm run build
- echo "构建完成 dist 大小: $(du -sh dist | cut -f1)"
# 检查产物体积是否异常增长
- |
SIZE=$(du -sk dist | cut -f1)
if [ "$SIZE" -gt 3072 ]; then
echo "产物体积超阈值: ${SIZE}KB"
exit 1
fi
artifacts:
paths: [dist/]
expire_in: 1 hour
缓存策略
# 依赖缓存:key 跟着 lock 文件走
key:
files: [package-lock.json]
# 构建缓存:key 跟着源码走
key:
prefix: "dist"
files: [src/**/*]
依赖缓存用 pull-push,CI 能写入供下次使用。构建产物用 pull,因为产物不该跨分支共享。
优化效果汇总
起点 158.7s
+ 依赖预编译 96.2s (-39%)
+ esbuild + splitChunks 51.3s (-47%)
+ Node 内存配置 45.1s (-12%)
+ Docker 缓存挂载 41.8s (-7%)
+ 迁移 Vite 22.3s (-47%)
累计:158.7s → 22.3s,提升 7.1 倍
开发环境的提升更大:HMR 从 3-8 秒降到 300ms 以内。
优化清单
先测量,不要凭感觉:
- 开启 Webpack
stats.timings和profile: true - 分析模块数量,确认为什么 node_modules 占大头
- 用 BundleAnalyzer 看产物构成
构建配置:
-
cache: { type: 'filesystem' } - node_modules 排除在 babel 转换之外
-
vue-loader开cacheDirectory - 压缩器换 esbuild
-
splitChunks按变更频率拆分 -
runtimeChunk: 'single'+moduleIds: 'deterministic' - 配置
NODE_OPTIONS=--max-old-space-size
Docker:
- 先
COPY package*.json再RUN npm ci - 用 BuildKit 的 cache mount 缓存 npm 目录
- 多阶段构建,运行镜像不含 node_modules
CI:
-
npm ci而非npm install - 用国内镜像源
- node_modules 目录缓存
- 加产物体积门禁,防止悄悄变大
三个经验
优化顺序很重要:先做缓存(依赖预编译 + filesystem cache),收益大且风险低;再换压缩器;最后才考虑换构建工具。前两步能解决 60% 的问题。
不要只看构建时间:开发环境的 HMR 体验对效率影响更大。Vite 的核心价值不是「构建快」,而是「启动快、改动即时反馈」。
产物体积门禁很有用:加一条 CI 检查,超阈值就失败。防止某天有人不小心引入了整个 lodash,构建还是绿的,但用户体验崩了。