一、技術堆疊選擇
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
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 = https://www.cnblogs.com/Jcloud/archive/2023/05/29/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 = https://www.cnblogs.com/Jcloud/archive/2023/05/29/{
...defaultParams,
}
}
const loading = ref(false)
const result = ref()
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 = https://www.cnblogs.com/Jcloud/archive/2023/05/29/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]+)*)?(?:\[.+\])?$',
// 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'],
},
}
五、附錄:技術堆疊圖譜
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/553708.html
標籤:其他
下一篇:返回列表
