一、技術棧選擇
1.代碼庫管理方式-Monorepo:将多個項目存放在同一個代碼庫中
▪選擇理由1:多個應用(可以按業務線産品粒度劃分)在同一個repo管理,便于統一管理代碼規範、共享工作流
▪選擇理由2:解決跨項目/應用之間實體層面的代碼複用,不用通過釋出/安裝npm包解決共享問題
2.依賴管理-PNPM:消除依賴提升、規範拓撲結構
▪選擇理由1:通過軟/硬連結方式,最大程度節省磁盤空間
▪選擇理由2:解決幽靈依賴問題,管理更清晰
3.建構工具-Vite:基于ESM和Rollup的建構工具
▪選擇理由:省去本地開發時的編譯過程,提升本地開發效率
4.前端架構-Vue3:Composition API
▪選擇理由:除了元件複用之外,還可以複用一些共同的邏輯狀态,比如請求接口loading與結果的邏輯
5.模拟接口傳回資料-Mockjs
▪選擇理由:前後端統一了資料結構後,即可分離開發,降低前端開發依賴,縮短開發周期
二、目錄結構設計:重點關注src部分
1.正常/簡單模式:根據檔案功能類型集中管理
```
mesh-fe
├── .husky #git送出代碼觸發
│ ├── commit-msg
│ └── pre-commit
├── mesh-server #依賴的node服務
│ ├── mock
│ │ └── data-service #mock接口傳回結果
│ └── package.json
├── README.md
├── package.json
├── pnpm-workspace.yaml #PNPM工作空間
├── .eslintignore #排除eslint檢查
├── .eslintrc.js #eslint配置
├── .gitignore
├── .stylelintignore #排除stylelint檢查
├── stylelint.config.js #style樣式規範
├── commitlint.config.js #git送出資訊規範
├── prettier.config.js #格式化配置
├── index.html #入口頁面
└── mesh-client #不同的web應用package
├── vite-vue3
├── src
├── api #api調用接口層
├── assets #靜态資源相關
├── components #公共元件
├── config #公共配置,如字典/枚舉等
├── hooks #邏輯複用
├── layout #router中使用的父布局元件
├── router #路由配置
├── stores #pinia全局狀态管理
├── types #ts類型聲明
├── utils
│ ├── index.ts
│ └── request.js #Axios接口請求封裝
├── views #主要頁面
├── main.ts #js入口
└── App.vue
```
2.基于domain領域模式:根據業務子產品集中管理
```
mesh-fe
├── .husky #git送出代碼觸發
│ ├── commit-msg
│ └── pre-commit
├── mesh-server #依賴的node服務
│ ├── mock
│ │ └── data-service #mock接口傳回結果
│ └── package.json
├── README.md
├── package.json
├── pnpm-workspace.yaml #PNPM工作空間
├── .eslintignore #排除eslint檢查
├── .eslintrc.js #eslint配置
├── .gitignore
├── .stylelintignore #排除stylelint檢查
├── stylelint.config.js #style樣式規範
├── commitlint.config.js #git送出資訊規範
├── prettier.config.js #格式化配置
├── index.html #入口頁面
└── mesh-client #不同的web應用package
├── vite-vue3
├── src #按業務領域劃分
├── assets #靜态資源相關
├── components #公共元件
├── domain #領域
│ ├── config.ts
│ ├── service.ts
│ ├── store.ts
│ ├── type.ts
├── hooks #邏輯複用
├── layout #router中使用的父布局元件
├── router #路由配置
├── utils
│ ├── index.ts
│ └── request.js #Axios接口請求封裝
├── views #主要頁面
├── main.ts #js入口
└── App.vue
```
可以根據具體業務場景,選擇以上2種方式其中之一。
三、搭建部分細節
1.Monorepo+PNPM集中管理多個應用(workspace)
▪根目錄建立pnpm-workspace.yaml,mesh-client檔案夾下每個應用都是一個package,之間可以互相添加本地依賴:pnpm install <name>
packages:
# all packages in direct subdirs of packages/
- 'mesh-client/*'
# exclude packages that are inside test directories
- '!**/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方法支援泛型
import axios, { AxiosError } from 'axios'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
// 建立 axios 執行個體
const service = axios.create({
baseURL: import.meta.env.VITE_APP_BASE_URL,
timeout: 1000 * 60 * 5, // 請求逾時時間
headers: { 'Content-Type': 'application/json;charset=UTF-8' },
})
const toLogin = (sso: string) => {
const cur = window.location.href
const url = `${sso}${encodeURIComponent(cur)}`
window.location.href = url
}
// 伺服器狀态碼錯誤處理
const handleError = (error: AxiosError) => {
if (error.response) {
switch (error.response.status) {
case 401:
// todo
toLogin(import.meta.env.VITE_APP_SSO)
break
// case 404:
// router.push('/404')
// break
// case 500:
// router.push('/500')
// break
default:
break
}
}
return Promise.reject(error)
}
// request interceptor
service.interceptors.request.use((config) => {
const token = ''
if (token) {
config.headers!['Access-Token'] = token // 讓每個請求攜帶自定義 token 請根據實際情況自行修改
}
return config
}, handleError)
// response interceptor
service.interceptors.response.use((response: AxiosResponse<ResponseData>) => {
const { code } = response.data
if (code === '10000') {
toLogin(import.meta.env.VITE_APP_SSO)
} else if (code !== '00000') {
// 抛出錯誤資訊,頁面處理
return Promise.reject(response.data)
}
// 傳回正确資料
return Promise.resolve(response)
// return response
}, handleError)
// 後端傳回資料結構泛型,根據實際項目調整
interface ResponseData<T = unknown> {
code: string
message: string
result: T
}
export const httpGet = async <T, D = any>(url: string, config?: AxiosRequestConfig<D>) => {
return service.get<ResponseData<T>>(url, config).then((res) => res.data)
}
export const httpPost = async <T, D = any>(
url: string,
data?: D,
config?: AxiosRequestConfig<D>,
) => {
return service.post<ResponseData<T>>(url, data, config).then((res) => res.data)
}
export { service as axios }
export type { ResponseData }
▪useRequest.ts封裝:基于vue3 Composition API,将請求參數、狀态以及結果等邏輯封裝複用
import { ref } from 'vue'
import type { Ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { ResponseData } from '@/utils/request'
export const useRequest = <T, P = any>(
api: (...args: P[]) => Promise<ResponseData<T>>,
defaultParams?: P,
) => {
const params = ref<P>() as Ref<P>
if (defaultParams) {
params.value = {
...defaultParams,
}
}
const loading = ref(false)
const result = ref<T>()
const fetchResource = async (...args: P[]) => {
loading.value = true
return api(...args)
.then((res) => {
if (!res?.result) return
result.value = res.result
})
.catch((err) => {
result.value = undefined
ElMessage({
message: typeof err === 'string' ? err : err?.message || 'error',
type: 'error',
offset: 80,
})
})
.finally(() => {
loading.value = false
})
}
return {
params,
loading,
result,
fetchResource,
}
}
▪API接口層
import { httpGet } from '@/utils/request'
const API = {
getLoginUserInfo: '/userInfo/getLoginUserInfo',
}
type UserInfo = {
userName: string
realName: string
}
export const getLoginUserInfoAPI = () => httpGet<UserInfo>(API.getLoginUserInfo)
▪頁面使用:接口傳回結果userInfo,可以自動推斷出UserInfo類型,
// 方式一:推薦
const {
loading,
result: userInfo,
fetchResource: getLoginUserInfo,
} = useRequest(getLoginUserInfoAPI)
// 方式二:不推薦,每次使用接口時都需要重複定義type
type UserInfo = {
userName: string
realName: string
}
const {
loading,
result: userInfo,
fetchResource: getLoginUserInfo,
} = useRequest<UserInfo>(getLoginUserInfoAPI)
onMounted(async () => {
await getLoginUserInfo()
if (!userInfo.value) return
const user = useUserStore()
user.$patch({
userName: userInfo.value.userName,
realName: userInfo.value.realName,
})
})
3.Mockjs模拟後端接口傳回資料
import Mock from 'mockjs'
const BASE_URL = '/api'
Mock.mock(`${BASE_URL}/user/list`, {
code: '00000',
message: '成功',
'result|10-20': [
{
uuid: '@guid',
name: '@name',
tag: '@title',
age: '@integer(18, 35)',
modifiedTime: '@datetime',
status: '@cword("01")',
},
],
})
四、統一規範
1.ESLint
注意:不同架構下,所需要的preset或plugin不同,建議将公共部分提取并配置在根目錄中,package中的eslint配置設定extends。
/* eslint-env node */
require('@rushstack/eslint-patch/modern-module-resolution')
module.exports = {
root: true,
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/eslint-config-typescript',
'@vue/eslint-config-prettier',
],
overrides: [
{
files: ['cypress/e2e/**.{cy,spec}.{js,ts,jsx,tsx}'],
extends: ['plugin:cypress/recommended'],
},
],
parserOptions: {
ecmaVersion: 'latest',
},
rules: {
'vue/no-deprecated-slot-attribute': 'off',
},
}
2.StyleLint
module.exports = {
extends: ['stylelint-config-standard', 'stylelint-config-prettier'],
plugins: ['stylelint-order'],
customSyntax: 'postcss-html',
rules: {
indentation: 2, //4空格
'selector-class-pattern':
'^(?:(?: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]+)*)?(?:\\[.+\\])?#39;,
// at-rule-no-unknown: 屏蔽一些scss等文法檢查
'at-rule-no-unknown': [true, { ignoreAtRules: ['mixin', 'extend', 'content', 'export'] }],
// css-next :global
'selector-pseudo-class-no-unknown': [
true,
{
ignorePseudoClasses: ['global', 'deep'],
},
],
'order/order': ['custom-properties', 'declarations'],
'order/properties-alphabetical-order': true,
},
}
3.Prettier
module.exports = {
printWidth: 100,
singleQuote: true,
trailingComma: 'all',
bracketSpacing: true,
jsxBracketSameLine: false,
tabWidth: 2,
semi: false,
}
4.CommitLint
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
['build', 'feat', 'fix', 'docs', 'style', 'refactor', 'test', 'chore', 'revert'],
],
'subject-full-stop': [0, 'never'],
'subject-case': [0, 'never'],
},
}
五、附錄
技術棧圖譜
作者:京東科技 牛志偉
内容來源:京東雲開發者社群