一、技术栈选择
1.代码库管理方式-Monorepo: 将多个项目存放在同一个代码库中
▪选择理由1:多个应用(可以按业务线产品粒度划分)在同一个repo管理,便于统一管理代码规范、共享工作流
▪选择理由2:解决跨项目/应用之间物理层面的代码复用,不用通过发布/安装npm包解决共享问题
2.依赖管理-PNPM: 消除依赖提升、规范拓扑结构
▪选择理由1:通过软/硬链接方式,最大程度节省磁盘空间
▪选择理由2:解决幽灵依赖问题,管理更清晰
3.构建工具-Vite:基于ESM和Rollup的构建工具
▪选择理由:省去本地开发时的编译过程,提升本地开发效率
4.前端框架-Vue3:Composition API
▪选择理由:除了组件复用之外,还可以复用一些共同的逻辑状态,比如请求接口loading与结果的逻辑
5.模拟接口返回数据-Mockjs
▪选择理由:前后端统一了数据结构后,即可分离开发,降低前端开发依赖,缩短开发周期
二、目录结构设计:重点关注src部分
1.常规/简单模式:根据文件功能类型集中管理
1``` 2mesh-fe 3├── .husky #git提交代码触发 4│ ├── commit-msg 5│ └── pre-commit 6├── mesh-server #依赖的node服务 7│ ├── mock 8│ │ └── data-service #mock接口返回结果 9│ └── package.json 10├── README.md 11├── package.json 12├── pnpm-workspace.yaml #PNPM工作空间 13├── .eslintignore #排除eslint检查 14├── .eslintrc.js #eslint配置 15├── .gitignore 16├── .stylelintignore #排除stylelint检查 17├── stylelint.config.js #style样式规范 18├── commitlint.config.js #git提交信息规范 19├── prettier.config.js #格式化配置 20├── index.html #入口页面 21└── mesh-client #不同的web应用package 22 ├── vite-vue3 23 ├── src 24 ├── api #api调用接口层 25 ├── assets #静态资源相关 26 ├── components #公共组件 27 ├── config #公共配置,如字典/枚举等 28 ├── hooks #逻辑复用 29 ├── layout #router中使用的父布局组件 30 ├── router #路由配置 31 ├── stores #pinia全局状态管理 32 ├── types #ts类型声明 33 ├── utils 34 │ ├── index.ts 35 │ └── request.js #Axios接口请求封装 36 ├── views #主要页面 37 ├── main.ts #js入口 38 └── App.vue 39```
2.基于domain领域模式:根据业务模块集中管理
1``` 2mesh-fe 3├── .husky #git提交代码触发 4│ ├── commit-msg 5│ └── pre-commit 6├── mesh-server #依赖的node服务 7│ ├── mock 8│ │ └── data-service #mock接口返回结果 9│ └── package.json 10├── README.md 11├── package.json 12├── pnpm-workspace.yaml #PNPM工作空间 13├── .eslintignore #排除eslint检查 14├── .eslintrc.js #eslint配置 15├── .gitignore 16├── .stylelintignore #排除stylelint检查 17├── stylelint.config.js #style样式规范 18├── commitlint.config.js #git提交信息规范 19├── prettier.config.js #格式化配置 20├── index.html #入口页面 21└── mesh-client #不同的web应用package 22 ├── vite-vue3 23 ├── src #按业务领域划分 24 ├── assets #静态资源相关 25 ├── components #公共组件 26 ├── domain #领域 27 │ ├── config.ts 28 │ ├── service.ts 29 │ ├── store.ts 30 │ ├── type.ts 31 ├── hooks #逻辑复用 32 ├── layout #router中使用的父布局组件 33 ├── router #路由配置 34 ├── utils 35 │ ├── index.ts 36 │ └── request.js #Axios接口请求封装 37 ├── views #主要页面 38 ├── main.ts #js入口 39 └── App.vue 40```
可以根据具体业务场景,选择以上2种方式其中之一。
三、搭建部分细节
1.Monorepo+PNPM集中管理多个应用(workspace)
▪根目录创建pnpm-workspace.yaml,mesh-client文件夹下每个应用都是一个package,之间可以相互添加本地依赖:pnpm install <name>
1packages: 2 # all packages in direct subdirs of packages/ 3 - 'mesh-client/*' 4 # exclude packages that are inside test directories 5 - '!**/test/**'
▪pnpm install #安装所有package中的依赖
▪pnpm install -w axios #将axios库安装到根目录
▪pnpm --filter | -F <name> <command> #执行某个package下的命令
▪与NPM安装的一些区别:
▪所有依赖都会安装到根目录node_modules/.pnpm下;
▪package中packages.json中下不会显示幽灵依赖(比如tslib@types/webpack-dev),需要显式安装,否则报错
▪安装的包首先会从当前workspace中查找,如果有存在则node_modules创建软连接指向本地workspace
▪"mock": "workspace:^1.0.0"
2.Vue3请求接口相关封装
▪request.ts封装:主要是对接口请求和返回做拦截处理,重写get/post方法支持泛型
1import axios, { AxiosError } from 'axios' 2import type { AxiosRequestConfig, AxiosResponse } from 'axios' 3 4// 创建 axios 实例 5const service = axios.create({ 6 baseURL: import.meta.env.VITE_APP_BASE_URL, 7 timeout: 1000 * 60 * 5, // 请求超时时间 8 headers: { 'Content-Type': 'application/json;charset=UTF-8' }, 9}) 10 11const toLogin = (sso: string) => { 12 const cur = window.location.href 13 const url = `${sso}${encodeURIComponent(cur)}` 14 window.location.href = url 15} 16 17// 服务器状态码错误处理 18const handleError = (error: AxiosError) => { 19 if (error.response) { 20 switch (error.response.status) { 21 case 401: 22 // todo 23 toLogin(import.meta.env.VITE_APP_SSO) 24 break 25 // case 404: 26 // router.push('/404') 27 // break 28 // case 500: 29 // router.push('/500') 30 // break 31 default: 32 break 33 } 34 } 35 return Promise.reject(error) 36} 37 38// request interceptor 39service.interceptors.request.use((config) => { 40 const token = '' 41 if (token) { 42 config.headers!['Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改 43 } 44 return config 45}, handleError) 46 47// response interceptor 48service.interceptors.response.use((response: AxiosResponse<ResponseData>) => { 49 const { code } = response.data 50 if (code === '10000') { 51 toLogin(import.meta.env.VITE_APP_SSO) 52 } else if (code !== '00000') { 53 // 抛出错误信息,页面处理 54 return Promise.reject(response.data) 55 } 56 // 返回正确数据 57 return Promise.resolve(response) 58 // return response 59}, handleError) 60 61// 后端返回数据结构泛型,根据实际项目调整 62interface ResponseData<T = unknown> { 63 code: string 64 message: string 65 result: T 66} 67 68export const httpGet = async <T, D = any>(url: string, config?: AxiosRequestConfig<D>) => { 69 return service.get<ResponseData<T>>(url, config).then((res) => res.data) 70} 71 72export const httpPost = async <T, D = any>( 73 url: string, 74 data?: D, 75 config?: AxiosRequestConfig<D>, 76) => { 77 return service.post<ResponseData<T>>(url, data, config).then((res) => res.data) 78} 79 80export { service as axios } 81 82export type { ResponseData }
▪useRequest.ts封装:基于vue3 Composition API,将请求参数、状态以及结果等逻辑封装复用
1import { ref } from 'vue' 2import type { Ref } from 'vue' 3import { ElMessage } from 'element-plus' 4import type { ResponseData } from '@/utils/request' 5export const useRequest = <T, P = any>( 6 api: (...args: P[]) => Promise<ResponseData<T>>, 7 defaultParams?: P, 8) => { 9 const params = ref<P>() as Ref<P> 10 if (defaultParams) { 11 params.value = { 12 ...defaultParams, 13 } 14 } 15 const loading = ref(false) 16 const result = ref<T>() 17 const fetchResource = async (...args: P[]) => { 18 loading.value = true 19 return api(...args) 20 .then((res) => { 21 if (!res?.result) return 22 result.value = res.result 23 }) 24 .catch((err) => { 25 result.value = undefined 26 ElMessage({ 27 message: typeof err === 'string' ? err : err?.message || 'error', 28 type: 'error', 29 offset: 80, 30 }) 31 }) 32 .finally(() => { 33 loading.value = false 34 }) 35 } 36 return { 37 params, 38 loading, 39 result, 40 fetchResource, 41 } 42}
▪API接口层
1import { httpGet } from '@/utils/request' 2 3const API = { 4 getLoginUserInfo: '/userInfo/getLoginUserInfo', 5} 6type UserInfo = { 7 userName: string 8 realName: string 9} 10export const getLoginUserInfoAPI = () => httpGet<UserInfo>(API.getLoginUserInfo)
▪页面使用:接口返回结果userInfo,可以自动推断出UserInfo类型,
1// 方式一:推荐 2const { 3 loading, 4 result: userInfo, 5 fetchResource: getLoginUserInfo, 6} = useRequest(getLoginUserInfoAPI) 7 8// 方式二:不推荐,每次使用接口时都需要重复定义type 9type UserInfo = { 10 userName: string 11 realName: string 12} 13const { 14 loading, 15 result: userInfo, 16 fetchResource: getLoginUserInfo, 17} = useRequest<UserInfo>(getLoginUserInfoAPI) 18 19onMounted(async () => { 20 await getLoginUserInfo() 21 if (!userInfo.value) return 22 const user = useUserStore() 23 user.$patch({ 24 userName: userInfo.value.userName, 25 realName: userInfo.value.realName, 26 }) 27})
3.Mockjs模拟后端接口返回数据
1import Mock from 'mockjs' 2const BASE_URL = '/api' 3Mock.mock(`${BASE_URL}/user/list`, { 4 code: '00000', 5 message: '成功', 6 'result|10-20': [ 7 { 8 uuid: '@guid', 9 name: '@name', 10 tag: '@title', 11 age: '@integer(18, 35)', 12 modifiedTime: '@datetime', 13 status: '@cword("01")', 14 }, 15 ], 16})
四、统一规范
1.ESLint
注意:不同框架下,所需要的preset或plugin不同,建议将公共部分提取并配置在根目录中,package中的eslint配置设置extends。
1/* eslint-env node */ 2require('@rushstack/eslint-patch/modern-module-resolution') 3 4module.exports = { 5 root: true, 6 extends: [ 7 'plugin:vue/vue3-essential', 8 'eslint:recommended', 9 '@vue/eslint-config-typescript', 10 '@vue/eslint-config-prettier', 11 ], 12 overrides: [ 13 { 14 files: ['cypress/e2e/**.{cy,spec}.{js,ts,jsx,tsx}'], 15 extends: ['plugin:cypress/recommended'], 16 }, 17 ], 18 parserOptions: { 19 ecmaVersion: 'latest', 20 }, 21 rules: { 22 'vue/no-deprecated-slot-attribute': 'off', 23 }, 24}
2.StyleLint
1module.exports = { 2 extends: ['stylelint-config-standard', 'stylelint-config-prettier'], 3 plugins: ['stylelint-order'], 4 customSyntax: 'postcss-html', 5 rules: { 6 indentation: 2, //4空格 7 'selector-class-pattern': 8 '^(?:(?:o|c|u|t|s|is|has|_|js|qa)-)?[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*(?:__[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*)?(?:--[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*)?(?:\[.+\])?$', 9 // at-rule-no-unknown: 屏蔽一些scss等语法检查 10 'at-rule-no-unknown': [true, { ignoreAtRules: ['mixin', 'extend', 'content', 'export'] }], 11 // css-next :global 12 'selector-pseudo-class-no-unknown': [ 13 true, 14 { 15 ignorePseudoClasses: ['global', 'deep'], 16 }, 17 ], 18 'order/order': ['custom-properties', 'declarations'], 19 'order/properties-alphabetical-order': true, 20 }, 21}
3.Prettier
1module.exports = { 2 printWidth: 100, 3 singleQuote: true, 4 trailingComma: 'all', 5 bracketSpacing: true, 6 jsxBracketSameLine: false, 7 tabWidth: 2, 8 semi: false, 9}
4.CommitLint
1module.exports = { 2 extends: ['@commitlint/config-conventional'], 3 rules: { 4 'type-enum': [ 5 2, 6 'always', 7 ['build', 'feat', 'fix', 'docs', 'style', 'refactor', 'test', 'chore', 'revert'], 8 ], 9 'subject-full-stop': [0, 'never'], 10 'subject-case': [0, 'never'], 11 }, 12}
五、附录:技术栈图谱
作者:京东科技 牛志伟
来源:京东云开发者社区
