一、技术栈抉择
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]+)*)?(?:\[.+\])?$',
// 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'],
},
}
发表回复