一、为什么工程化如此关键?
工程化的目标是:让项目更快、更稳、更易协作与维护。
尤其在企业级项目中,比如广告投放平台:
- 功能复杂,迭代频繁
- 多端部署,环境多变
- 多人协作,容错成本高
唯有一套高质量工程体系,才能让产品快速、稳定地从“代码”变成“用户可访问的系统”。
二、项目构建配置优化
使用 Vite 替代 Webpack:
// vite.config.ts
import vue from '@vitejs/plugin-vue'
import path from 'path'
export default {
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
},
build: {
target: 'es2015',
outDir: 'dist',
rollupOptions: {
output: {
manualChunks: {
vendor: ['vue', 'axios', 'pinia']
}
}
}
}
}
按需打包、CDN 加速资源,构建体积控制在 800KB 以下。
三、多环境配置管理
不同环境注入不同配置:
.env.development
VITE_API_BASE=/api/test
.env.production
VITE_API_BASE=https://api.prod.com
项目中读取:
axios.defaults.baseURL = import.meta.env.VITE_API_BASE
四、GitLab CI 自动化部署流程
.gitlab-ci.yml 示例:
stages:
- build
- deploy
build:
stage: build
image: node:18
script:
- npm ci
- npm run build
artifacts:
paths:
- dist
prod-deploy:
stage: deploy
script:
- scp -r dist/* user@host:/var/www/html/ad-platform
only:
- master
每次合并 master 自动构建并上传到服务器,无需人工介入。
五、部署策略设计:版本安全与回滚机制
采用 Nginx 静态部署,目录结构如下:
/var/www/html
├── v1.0.0/
├── v1.0.1/
└── current -> v1.0.1
版本发布脚本:
BUILD_ID=$(date +%Y%m%d%H%M)
scp -r dist/ user@host:/var/www/html/$BUILD_ID
ssh user@host "ln -sfn /var/www/html/$BUILD_ID /var/www/html/current"
优点:
- 每次部署有独立目录,方便回滚
- current 是软链接,随时切换版本
六、缓存控制与资源命中优化
避免静态资源缓存导致页面错乱:
build: {
assetsDir: 'static',
assetsInlineLimit: 4096,
rollupOptions: {
output: {
entryFileNames: 'static/js/[name].[hash].js',
chunkFileNames: 'static/js/[name].[hash].js',
assetFileNames: 'static/[ext]/[name].[hash].[ext]'
}
}
}
HTML 文件不加 hash,保证能找到最新入口:
location / {
try_files $uri /index.html;
}
七、错误监控与性能上报
接入 Sentry:
import * as Sentry from '@sentry/vue'
Sentry.init({
app,
dsn: 'https://xxx@sentry.io/xxx',
integrations: [new Integrations.BrowserTracing()],
tracesSampleRate: 1.0
})
接入 Web Vitals:
import { getCLS, getFID, getLCP } from 'web-vitals'
getCLS(console.log)
getFID(console.log)
getLCP(console.log)
八、团队协作与分支策略
- 使用 Git flow 分支模型:
master、dev、feature/* - 每个 MR 要求代码审查 + lint pass + 单元测试通过
- 使用 commit lint + changelog 自动生成版本日志
fix(ad-form): 修复预算校验逻辑
feat(report): 新增导出报表接口
九、总结:什么才是极致的前端工程?
不是装了多少插件,而是:
- 任何人拉代码都能跑
- 合并后能立即部署上线
- 报错能第一时间收到通知
- 有回滚、缓存、版本、安全等机制兜底
这套工程体系,已成功支撑广告平台数十次稳定迭代。