目录
一、工程化基石:Vue3+Vite 项目搭建
1.1 极速初始化
# 推荐使用 pnpm 初始化项目
pnpm create vite@latest vue-elementplus-project --template vue-ts
cd vue-elementplus-project
pnpm install
1.2 核心配置优化
1.2.1 Vite 配置增强
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
vue(),
Components({
resolvers: [ElementPlusResolver()]
})
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
css: {
preprocessorOptions: {
scss: {
additionalData: `@use "@/styles/element/index.scss" as *;`
}
}
}
})
1.2.2 代码规范体系
# 安装依赖
pnpm add -D eslint prettier @typescript-eslint/eslint-plugin @typescript-eslint/parser
// .eslintrc.cjs
module.exports = {
root: true,
env: {
node: true
},
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/typescript/recommended'
],
parserOptions: {
ecmaVersion: 2020
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
}
}
二、ElementPlus 深度集成
2.1 按需加载配置
typescript
// vite.config.ts
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
Components({
resolvers: [
ElementPlusResolver({
importStyle: 'sass'
})
]
})
2.2 主题定制方案
2.2.1 基础变量覆盖
scss
// src/styles/element/index.scss
@forward 'element-plus/theme-chalk/src/common/var.scss' with (
$colors: (
'primary': (
'base': #409eff
)
)
);
2.2.2 动态主题切换
// composables/useTheme.ts
import { computed } from 'vue'
import { useElementPlus } from 'element-plus'
export function useDynamicTheme() {
const { theme } = useElementPlus()
const currentTheme = computed({
get: () => theme.value,
set: (val) => {
theme.value = val
document.documentElement.setAttribute('data-theme', val)
}
})
return { currentTheme }
}
2.3 国际化配置
// main.ts
import { createI18n } from 'vue-i18n'
import enLocale from 'element-plus/lib/locale/lang/en'
import zhLocale from 'element-plus/lib/locale/lang/zh-cn'
const i18n = createI18n({
locale: 'zh-cn',
messages: {
'zh-cn': {
...zhLocale,
app: {
title: 'Vue工程化实战'
}
},
en: {
...enLocale,
app: {
title: 'Vue Engineering Practice'
}
}
}
})
app.use(i18n)
三、工程化核心实践
3.1 目录结构设计
├── public # 静态资源
├── src
│ ├── api # 接口层
│ ├── assets # 静态资源
│ ├── components # 基础组件
│ ├── composables # 组合式函数
│ ├── directives # 自定义指令
│ ├── hooks # 全局钩子
│ ├── layouts # 布局组件
│ ├── router # 路由配置
│ ├── store # 状态管理
│ ├── styles # 全局样式
│ ├── utils # 工具函数
│ └── views # 业务页面
├── tests # 测试目录
└── types # 类型定义
3.2 自动化工具链
3.2.1 提交规范
pnpm add -D commitizen cz-conventional-changelog
echo '{ "path": "cz-conventional-changelog" }' > .czrc
3.2.2 持续集成
# .github/workflows/build.yml
name: Build
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '18'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build
run: pnpm run build
四、性能优化实战
4.1 打包优化策略
// vite.config.ts
export default defineConfig({
build: {
target: 'es2020',
chunkSizeWarningLimit: 1500,
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
return id.toString().split('node_modules/')[1].split('/')[0].toString();
}
}
}
}
}
})
4.2 图片优化方案
pnpm add -D vite-plugin-imagemin
// vite.config.ts
import viteImagemin from 'vite-plugin-imagemin'
plugins: [
viteImagemin({
gifsicle: { optimizationLevel: 7 },
optipng: { optimizationLevel: 7 },
mozjpeg: { quality: 20 },
pngquant: { quality: [0.8, 0.9], speed: 4 },
svgo: {
plugins: [
{ name: 'removeViewBox' },
{ name: 'cleanupIDs', active: false }
]
}
})
]
五、实战案例:企业级后台系统
5.1 权限管理实现
// store/modules/auth.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useAuthStore = defineStore('auth', () => {
const roles = ref<string[]>([])
const permissions = ref<string[]>([])
function setUserInfo(userInfo: UserInfo) {
roles.value = userInfo.roles
permissions.value = userInfo.permissions
}
function hasPermission(permission: string) {
return permissions.value.includes(permission)
}
return { roles, permissions, setUserInfo, hasPermission }
})
5.2 动态路由加载
// router/index.ts
import { createRouter, createWebHashHistory } from 'vue-router'
import { useAuthStore } from '@/store'
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/login',
component: () => import('@/views/login/index.vue'),
meta: { requiresAuth: false }
}
]
})
router.beforeEach((to, from, next) => {
const authStore = useAuthStore()
if (to.meta.requiresAuth && !authStore.roles.length) {
next('/login')
} else {
next()
}
})
六、生产部署方案
6.1 构建产物分析
pnpm run build --report
6.2 CDN 加速配置
6.3 容器化部署
# Dockerfile
FROM node:18-alpine as build
WORKDIR /app
COPY package*.json ./
RUN pnpm install --frozen-lockfile
COPY . .
RUN pnpm run build
FROM nginx:1.23-alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
七、延伸学习资源
7.1 官方文档
7.2 优质插件
插件名称 | 功能描述 |
---|---|
unplugin-vue-components | 组件自动导入 |
vite-plugin-style-import | 样式按需加载 |
@vueuse/core | 实用组合式函数 |
7.3 学习社区
八、常见问题排查
8.1 样式冲突解决方案
// 全局样式覆盖
::v-deep .el-table {
font-size: 14px;
}
8.2 打包体积过大分析
# 安装包体积分析工具
pnpm add -D webpack-bundle-analyzer
// vite.config.ts
import { visualizer } from 'rollup-plugin-visualizer'
plugins: [
visualizer({
open: true,
gzipSize: true,
brotliSize: true
})
]
8.3 性能监控方案
// 性能监控配置
import { createApp } from 'vue'
import { createPerfume } from 'perfume.js'
const perfume = createPerfume()
perfume.track('app-load', 'App Load')
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
perfume.trackEnd('app-load')
九、总结与展望
本文从工程化视角深入解析了 Vue3+ElementPlus 的全链路开发实践,涵盖项目初始化、核心配置、主题定制、国际化、性能优化、实战案例及生产部署等关键环节。通过结合最新的 Vite 构建工具和 ElementPlus 的高级特性,帮助开发者快速搭建高性能、可维护的企业级应用。未来,随着 Vue3 生态的持续完善和 ElementPlus 的功能迭代,前端工程化将朝着更智能、更高效的方向发展,为开发者带来更优质的开发体验。