一、技術(shù)棧選擇
1.代碼庫管理方式-Monorepo: 將多個(gè)項(xiàng)目存放在同一個(gè)代碼庫中
?選擇理由1:多個(gè)應(yīng)用(可以按業(yè)務(wù)線產(chǎn)品粒度劃分)在同一個(gè)repo管理,便于統(tǒng)一管理代碼規(guī)范、共享工作流
?選擇理由2:解決跨項(xiàng)目/應(yīng)用之間物理層面的代碼復(fù)用,不用通過發(fā)布/安裝npm包解決共享問題
2.依賴管理-PNPM: 消除依賴提升、規(guī)范拓?fù)浣Y(jié)構(gòu)
?選擇理由1:通過軟/硬鏈接方式,最大程度節(jié)省磁盤空間
?選擇理由2:解決幽靈依賴問題,管理更清晰
3.構(gòu)建工具-Vite:基于ESM和Rollup的構(gòu)建工具
?選擇理由:省去本地開發(fā)時(shí)的編譯過程,提升本地開發(fā)效率
4.前端框架-Vue3:Composition API
?選擇理由:除了組件復(fù)用之外,還可以復(fù)用一些共同的邏輯狀態(tài),比如請(qǐng)求接口loading與結(jié)果的邏輯
5.模擬接口返回?cái)?shù)據(jù)-Mockjs
?選擇理由:前后端統(tǒng)一了數(shù)據(jù)結(jié)構(gòu)后,即可分離開發(fā),降低前端開發(fā)依賴,縮短開發(fā)周期
二、目錄結(jié)構(gòu)設(shè)計(jì):重點(diǎn)關(guān)注src部分
1.常規(guī)/簡單模式:根據(jù)文件功能類型集中管理
mesh-fe
├── .husky #git提交代碼觸發(fā)
│ ├── commit-msg
│ └── pre-commit
├── mesh-server #依賴的node服務(wù)
│ ├── mock
│ │ └── data-service #mock接口返回結(jié)果
│ └── package.json
├── README.md
├── package.json
├── pnpm-workspace.yaml #PNPM工作空間
├── .eslintignore #排除eslint檢查
├── .eslintrc.js #eslint配置
├── .gitignore
├── .stylelintignore #排除stylelint檢查
├── stylelint.config.js #style樣式規(guī)范
├── commitlint.config.js #git提交信息規(guī)范
├── prettier.config.js #格式化配置
├── index.html #入口頁面
└── mesh-client #不同的web應(yīng)用package
├── vite-vue3
├── src
├── api #api調(diào)用接口層
├── assets #靜態(tài)資源相關(guān)
├── components #公共組件
├── config #公共配置,如字典/枚舉等
├── hooks #邏輯復(fù)用
├── layout #router中使用的父布局組件
├── router #路由配置
├── stores #pinia全局狀態(tài)管理
├── types #ts類型聲明
├── utils
│ ├── index.ts
│ └── request.js #Axios接口請(qǐng)求封裝
├── views #主要頁面
├── main.ts #js入口
└── App.vue
2.基于domain領(lǐng)域模式:根據(jù)業(yè)務(wù)模塊集中管理
mesh-fe
├── .husky #git提交代碼觸發(fā)
│ ├── commit-msg
│ └── pre-commit
├── mesh-server #依賴的node服務(wù)
│ ├── mock
│ │ └── data-service #mock接口返回結(jié)果
│ └── package.json
├── README.md
├── package.json
├── pnpm-workspace.yaml #PNPM工作空間
├── .eslintignore #排除eslint檢查
├── .eslintrc.js #eslint配置
├── .gitignore
├── .stylelintignore #排除stylelint檢查
├── stylelint.config.js #style樣式規(guī)范
├── commitlint.config.js #git提交信息規(guī)范
├── prettier.config.js #格式化配置
├── index.html #入口頁面
└── mesh-client #不同的web應(yīng)用package
├── vite-vue3
├── src #按業(yè)務(wù)領(lǐng)域劃分
├── assets #靜態(tài)資源相關(guān)
├── components #公共組件
├── domain #領(lǐng)域
│ ├── config.ts
│ ├── service.ts
│ ├── store.ts
│ ├── type.ts
├── hooks #邏輯復(fù)用
├── layout #router中使用的父布局組件
├── router #路由配置
├── utils
│ ├── index.ts
│ └── request.js #Axios接口請(qǐng)求封裝
├── views #主要頁面
├── main.ts #js入口
└── App.vue
可以根據(jù)具體業(yè)務(wù)場(chǎng)景,選擇以上2種方式其中之一。
三、搭建部分細(xì)節(jié)
1.Monorepo+PNPM集中管理多個(gè)應(yīng)用(workspace)
?根目錄創(chuàng)建pnpm-workspace.yaml,mesh-client文件夾下每個(gè)應(yīng)用都是一個(gè)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> #執(zhí)行某個(gè)package下的命令
?與NPM安裝的一些區(qū)別:
?所有依賴都會(huì)安裝到根目錄node_modules/.pnpm下;
?package中packages.json中下不會(huì)顯示幽靈依賴(比如tslib@types/webpack-dev),需要顯式安裝,否則報(bào)錯(cuò)
?安裝的包首先會(huì)從當(dāng)前workspace中查找,如果有存在則node_modules創(chuàng)建軟連接指向本地workspace
?"mock": "workspace:^1.0.0"
2.Vue3請(qǐng)求接口相關(guān)封裝
?request.ts封裝:主要是對(duì)接口請(qǐng)求和返回做攔截處理,重寫get/post方法支持泛型
import axios, { AxiosError } from 'axios'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
// 創(chuàng)建 axios 實(shí)例
const service = axios.create({
baseURL: import.meta.env.VITE_APP_BASE_URL,
timeout: 1000 * 60 * 5, // 請(qǐng)求超時(shí)時(shí)間
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
}
// 服務(wù)器狀態(tài)碼錯(cuò)誤處理
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 // 讓每個(gè)請(qǐng)求攜帶自定義 token 請(qǐng)根據(jù)實(shí)際情況自行修改
}
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') {
// 拋出錯(cuò)誤信息,頁面處理
return Promise.reject(response.data)
}
// 返回正確數(shù)據(jù)
return Promise.resolve(response)
// return response
}, handleError)
// 后端返回?cái)?shù)據(jù)結(jié)構(gòu)泛型,根據(jù)實(shí)際項(xiàng)目調(diào)整
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,將請(qǐng)求參數(shù)、狀態(tài)以及結(jié)果等邏輯封裝復(fù)用
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)
?頁面使用:接口返回結(jié)果userInfo,可以自動(dòng)推斷出UserInfo類型,
// 方式一:推薦
const {
loading,
result: userInfo,
fetchResource: getLoginUserInfo,
} = useRequest(getLoginUserInfoAPI)
// 方式二:不推薦,每次使用接口時(shí)都需要重復(fù)定義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模擬后端接口返回?cái)?shù)據(jù)
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")',
},
],
})
四、統(tǒng)一規(guī)范
1.ESLint
注意:不同框架下,所需要的preset或plugin不同,建議將公共部分提取并配置在根目錄中,package中的eslint配置設(shè)置extends。文章來源:http://www.zghlxwxcb.cn/news/detail-463074.html
/* 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'],
},
}
五、附錄:技術(shù)棧圖譜
文章來源地址http://www.zghlxwxcb.cn/news/detail-463074.html
到了這里,關(guān)于最佳實(shí)踐:基于vite3的monorepo前端工程搭建的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!