Vue3+Vite工程化实践:打造企业级前端开发流程
📚 本文将分享Vue3+Vite项目的完整工程化解决方案,包含项目规范、构建优化、自动化部署等内容。
作者:沈大大
更新时间:2025-03-09
一、项目规范化
1. ESLint配置
javascript
// .eslintrc.js
module.exports = {
root: true,
env: {
browser: true,
node: true,
es2021: true,
},
extends: [
'plugin:vue/vue3-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
],
parser: 'vue-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser',
ecmaVersion: 2021,
},
rules: {
// Vue3特定规则
'vue/multi-word-component-names': 'off',
'vue/no-v-html': 'off',
// TypeScript规则
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
},
}
2. Git提交规范
javascript
// commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
[
'feat', // 新功能
'fix', // 修复
'docs', // 文档
'style', // 格式
'refactor', // 重构
'perf', // 性能
'test', // 测试
'chore', // 构建
],
],
},
}
3. 自动格式化
json
// .prettierrc
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2,
"endOfLine": "auto"
}
二、构建优化
1. Vite配置优化
typescript
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { visualizer } from 'rollup-plugin-visualizer';
import compression from 'vite-plugin-compression';
export default defineConfig({
plugins: [
vue(),
// 构建分析
visualizer({
open: true,
gzipSize: true,
}),
// Gzip压缩
compression({
algorithm: 'gzip',
ext: '.gz',
}),
],
build: {
// 构建优化
target: 'es2015',
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
},
},
// 分包策略
rollupOptions: {
output: {
manualChunks: {
'vue-vendor': ['vue', 'vue-router', 'pinia'],
'element-plus': ['element-plus'],
'echarts': ['echarts'],
},
},
},
},
});
2. 环境配置
typescript
// .env.development
VITE_API_BASE_URL=http://dev-api.example.com
VITE_APP_TITLE=开发环境
// .env.production
VITE_API_BASE_URL=http://api.example.com
VITE_APP_TITLE=生产环境
// 使用环境变量
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
三、自动化部署
1. Docker部署
dockerfile
# Dockerfile
FROM node:16-alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
2. Jenkins流水线
groovy
// Jenkinsfile
pipeline {
agent any
environment {
DOCKER_IMAGE = 'your-registry/your-app:${BUILD_NUMBER}'
}
stages {
stage('Build') {
steps {
sh 'npm install'
sh 'npm run build'
}
}
stage('Test') {
steps {
sh 'npm run test:unit'
}
}
stage('Docker Build') {
steps {
sh "docker build -t ${DOCKER_IMAGE} ."
}
}
stage('Deploy') {
steps {
sh "docker push ${DOCKER_IMAGE}"
sh "kubectl set image deployment/your-app your-app=${DOCKER_IMAGE}"
}
}
}
}
四、开发规范
1. 目录结构规范
bash
src/
├── api/ # API接口
├── assets/ # 静态资源
├── components/ # 公共组件
├── composables/ # 组合式函数
├── config/ # 配置文件
├── directives/ # 自定义指令
├── hooks/ # 钩子函数
├── layouts/ # 布局组件
├── router/ # 路由配置
├── stores/ # 状态管理
├── styles/ # 全局样式
├── types/ # 类型定义
├── utils/ # 工具函数
└── views/ # 页面组件
2. 命名规范
typescript
// 组件命名
// components/BaseButton.vue
export default defineComponent({
name: 'BaseButton',
});
// 文件命名
// utils/date-format.ts
export function dateFormat() {}
// 变量命名
const userInfo = ref<UserInfo | null>(null);
const isLoading = ref(false);
const handleSubmit = () => {};
五、性能优化
1. 路由懒加载
typescript
// router/index.ts
const routes = [
{
path: '/dashboard',
component: () => import('@/views/dashboard/index.vue'),
children: [
{
path: 'analysis',
component: () => import('@/views/dashboard/analysis.vue'),
},
],
},
];
2. 图片优化
typescript
// vite.config.ts
import imagemin from 'vite-plugin-imagemin';
export default defineConfig({
plugins: [
imagemin({
gifsicle: {
optimizationLevel: 7,
interlaced: false,
},
optipng: {
optimizationLevel: 7,
},
mozjpeg: {
quality: 80,
},
pngquant: {
quality: [0.8, 0.9],
speed: 4,
},
svgo: {
plugins: [
{
name: 'removeViewBox',
},
{
name: 'removeEmptyAttrs',
active: false,
},
],
},
}),
],
});
六、监控与日志
1. 错误监控
typescript
// utils/error-handler.ts
export function setupErrorHandler() {
// 全局错误处理
window.onerror = function(message, source, lineno, colno, error) {
console.error('Global error:', {
message,
source,
lineno,
colno,
error,
});
// 上报错误
reportError({
type: 'js',
message,
source,
lineno,
colno,
error,
});
return true;
};
// Vue错误处理
app.config.errorHandler = (error, instance, info) => {
console.error('Vue error:', error);
// 上报错误
reportError({
type: 'vue',
error,
info,
});
};
}
2. 性能监控
typescript
// utils/performance-monitor.ts
export function setupPerformanceMonitor() {
// 监控页面加载性能
window.addEventListener('load', () => {
const timing = performance.timing;
const metrics = {
// DNS查询时间
dns: timing.domainLookupEnd - timing.domainLookupStart,
// TCP连接时间
tcp: timing.connectEnd - timing.connectStart,
// 首字节时间
ttfb: timing.responseStart - timing.requestStart,
// DOM解析时间
domParse: timing.domComplete - timing.domInteractive,
// 页面完全加载时间
loadComplete: timing.loadEventEnd - timing.navigationStart,
};
// 上报性能数据
reportPerformance(metrics);
});
}
总结
本文介绍了Vue3+Vite项目的完整工程化解决方案,包含了项目规范、构建优化、自动化部署等多个方面。这些实践可以帮助你搭建一个更加规范和高效的前端开发环境。
参考资料
如果觉得文章对你有帮助,请点个赞!
关注我,持续分享前端工程化实践经验!
#Vue3 #Vite #前端工程化 #自动化部署