最佳實踐:基於vite3的monorepo前端工程搭建 | 京東雲技術團隊

一、技術棧選擇

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'],
  },
}

五、附錄:技術棧圖譜

作者:京東科技 牛志偉

來源:京東雲開發者社區

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章