Redian新闻
>
基于vite3的monorepo前端工程搭建

基于vite3的monorepo前端工程搭建

公众号新闻

来源 | OSCHINA 社区

作者 | 京东云开发者-京东科技 牛志伟

原文链接:https://my.oschina.net/u/4090830/blog/9428865

一、技术栈选择

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'],
},
}
五、附录:技术栈图谱


END



十年磨一剑,开源中国新使命



这里有最新开源资讯、软件更新、技术干货等内容

点这里 ↓↓↓ 记得 关注✔ 标星⭐ 哦


微信扫码关注该文公众号作者

戳这里提交新闻线索和高质量文章给我们。
相关阅读
60s带你看大疆Inspire3影视航拍无人机!致远电子冲刺深交所:拟募资8亿 周立功与陈智红IPO前离婚旧金山艺术宫(Palace of Fine Arts),艺术建筑柏林工大也有自己的Döner店了!前端工作两年,应该把精力放在 Vue 上还是 JS、React、工程化上?| 极客时间Redmi 新机再曝,Redmi Note 13、Redmi K70期待哪款?分布式PostgreSQL基准测试:Azure Cosmos DB、CockroachDB和YugabyteDB最抢手岗位之一 | 前端工程师求职1V1定制计划随时开课!Spring 中 @NotEmpty、@NotBlank、@NotNull,傻傻分不清楚!ICCV 2023 | K400首次90%准确率!UniFormerV2开源:基于ViT的高效视频识别春季户外探索开始!Mountain Warehouse3合一夹克$89.99趣图:前端工程师看到要发狂的窗户一个前端大佬的十年回顾 | 漫画前端的前世今生双非一本,均分84,托福96,GRE332,可以申请到美国什么大学?蒸馏也能Step-by-Step:新方法让小模型也能媲美2000倍体量大模型一“mo”做事亿“mo”当!你加入“momo大军”了吗?英伟达H100霸榜权威AI性能测试,11分钟搞定基于GPT-3的大模型训练对话ASCO前主席:四项重磅研究冲击肿瘤治疗前端十年回顾 | 漫画前端的前世今生前端工程师面试的五大注意事项双林奇案录第三部之天禅寺:第十九节无中介费【E3】近BU/BC豪华高级公寓E3 studio 2763+ 1b 3195+ 2b 3928+国际青少年创新创业大赛! International Youth Innovation&Entrepreneur Contest长篇小说《如絮》第一百一十三章 旧金山-1956年 温柔地爱我Step-by-Step,一步步教会注册护士全家移民美国规划(上)双林奇案录第三部之天禅寺:第二十节Regular Monthly Reminder for U.S. Citizens|每月例行美国公民STEP提醒相见恨晚的背单词方法,轻松搞定GRE3000必考词,超上头!如何基于Llama 2搭建自己的大模型?8月26日,4位技术大牛手把手教你一“mo”做事亿“mo”当......神秘“momo”们,到底是谁?克罗地亚杜布罗夫尼克(Dubrovnik),海边古城大疆Inspire3首发开箱,影视航拍无人机来了!祝贺Replit估值11.6亿美金【AMINO被投企业】AI代码生成平台Replit融资9740万美金China Proposes To Regulate AI-Generated ContentNote“超大杯”新机线稿曝光,预计为Redmi Note 13 Pro+
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。