vue3+ts項目初始化
cms實戰項目
建立項目
vue create vue3_ts_master_cms
選擇手動配置
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLhNGNwITZ4IjYlhTNkRGOhRDZzQjM0UDMiF2YmhjN2YzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
出現以下圖,項目建立成功
內建各種element-plus
按需自動導入,先安裝官網提供的兩個插件
unplugin-vue-components
和
unplugin-auto-import
這兩款插件
npm install -D unplugin-vue-components unplugin-auto-import
導入後會出現圖示或者樣式錯位的情況
解決方法:安裝圖示庫并再
main.ts
注冊
yarn add @element-plus/icons-vue
在
main.ts
裡
import 'element-plus/theme-chalk/el-loading.css'
import 'element-plus/theme-chalk/el-message.css'
import 'element-plus/theme-chalk/el-notification.css'
import 'element-plus/theme-chalk/el-message-box.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
//注冊element plus 的圖示
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
修改vue.config.js檔案
const { defineConfig } = require("@vue/cli-service");
const AutoImport = require("unplugin-auto-import/webpack");
const Components = require("unplugin-vue-components/webpack");
const { ElementPlusResolver } = require("unplugin-vue-components/resolvers");
module.exports = defineConfig({
transpileDependencies: true,
configureWebpack: {
plugins: [
AutoImport({
resolvers: [ElementPlusResolver()]
}),
Components({
resolvers: [ElementPlusResolver()]
})
]
},
});
內建editorconfig配置
**目的:統一編碼風格。**EditorConfig 有助于為不同 IDE 編輯器上處理同一項目的多個開發人員維護一緻的編碼風格。
根目錄下建立
.editorconfig
檔案
root = true
[*] # 表示所有檔案适用
charset = utf-8 # 設定檔案字元集為 utf-8
indent_style = space # 縮進風格(tab | space)
indent_size = 2 # 縮進大小
end_of_line = lf # 控制換行類型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字元
insert_final_newline = true # 始終在檔案末尾插入一個新行
[*.md] # 表示僅 md 檔案适用以下規則
max_line_length = off
trim_trailing_whitespace = false
使用工具prettier
作用:格式化代碼工具
- 安裝
- 配置:建立
·檔案.prettierrc
- useTabs:使用tab縮進還是空格縮進,選擇false;
- tabWidth:tab是空格的情況下,是幾個空格,選擇2個;
- printWidth:當行字元的長度,推薦80,也有人喜歡100或者120;
- singleQuote:使用單引号還是雙引号,選擇true,使用單引号;
- trailingComma:在多行輸入的尾逗号是否添加,設定為
;none
- semi:語句末尾是否要加分号,預設值true,選擇false表示不加;
{
"useTabs": false,
"tabWidth": 2,
"printWidth": 80,
"singleQuote": true,
"trailingComma": "none",
"semi": false
}
在使用vscode編輯器時,安裝插件
Prettier - Code formatter
,儲存時會自動調用上面的配置進行格式化
不是vscode編輯器,需要指令行調用
npm run prettier
想要這行指令起作用,需要在package.json進行配置
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"prettier": "prettier --write ."
},
如果建立項目時選擇的不是esline+prettier,這個配置就會和eslinet沖突
如果是建立項目時就自動安裝了這兩個插件(我們這個是選擇eslint+prettier的)
解決方法:
- 安裝
eslint-plugin-prettier
eslint-config-prettier
npm i eslint-plugin-prettier eslint-config-prettier -D
- 添加prettier插件:在
檔案中.eslintrc.js
module.exports = {
root: true,
env: {
node: true,
},
extends: [
"plugin:vue/vue3-essential",
"eslint:recommended",
"@vue/typescript/recommended",
"plugin:prettier/recommended",
],
parserOptions: {
ecmaVersion: 2020,
},
rules: {
"no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
"no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
},
};
內建git Husky 來檢測集修複,git commit前代碼的規範
作用:開發成員在
git代碼前
,先檢查代碼是否符合規範,并格式化代碼
雖然我們已經要求項目使用eslint了,但是不能保證組員送出代碼之前都将eslint中的問題解決掉了:
- 也就是我們希望保證代碼倉庫中的代碼都是符合eslint規範的;
- 那麼我們需要在組員執行
指令的時候對其進行校驗,如果不符合eslint規範,那麼自動通過規範進行修複;git commit
那麼如何做到這一點呢?可以通過Husky工具:
- husky是一個git hook工具,可以幫助我們觸發git送出的各個階段:pre-commit、commit-msg、pre-push
如何使用husky呢?
這裡我們可以使用自動配置指令:
這裡會做三件事:(上面的指令會幫我們完成以下三個步驟,不需要手動添加)
1.安裝husky相關的依賴:
2.在項目跟目錄下建立
.husky
檔案夾
3.在package.json中添加一個腳本:
配置commit前需要執行的指令,修改pre-commit檔案
把 npm test 改為 npm run lint
內建Commitizen來統一git commit規範
作用:用來規範 git commit送出時,按照統一的風格送出,作用于
commit
通常我們的git commit會按照統一的風格來送出,這樣可以快速定位每次送出的内容,友善之後對版本進行控制。
- 安裝
Commitizen
- 安裝
,并且初始化cz-conventional-changelog
:cz-conventional-changelog
npx commitizen init cz-conventional-changelog --save-dev --save-exact
這個指令做了兩件事
- 按照了
cz-conventional-changelog
- 在
中進行配置package.json
這個時候我們送出代碼需要使用
npx cz
:
- 第一步是選擇type,本次更新的類型
Type | 作用 |
---|---|
feat | 新增特性 (feature) |
fix | 修複 Bug(bug fix) |
docs | 修改文檔 (documentation) |
style | 代碼格式修改(white-space, formatting, missing semi colons, etc) |
refactor | 代碼重構(refactor) |
perf | 改善性能(A code change that improves performance) |
test | 測試(when adding missing tests) |
build | 變更項目建構或外部依賴(例如 scopes: webpack、gulp、npm 等) |
ci | 更改持續內建軟體的配置檔案和 package 中的 scripts 指令,例如 scopes: Travis, Circle 等 |
chore | 變更建構流程或輔助工具(比如更改測試環境) |
revert | 代碼回退 |
第二步選擇本次修改的範圍(作用域)(也就是改了哪些闆塊【檔案或代碼】eg:login)
第三步選擇送出的資訊(eg:“登入子產品已完成”)
第四步送出詳細的描述資訊(詳細資訊,沒有可回車跳過)
第五步是否是一次重大的更改(yes/No,直接回車為No,(日常開發一般也為NO,除非有版本等大更新))
第六步是否影響某個open issue(這次送出的代碼是否影響其他開發者,一般為no)
我們也可以在scripts中建構一個指令來執行 cz:
在package.json檔案配置,使其他開發人員直接使用
- 配置
package.json
"scripts": {
...
"prettier": "prettier --writer .",
"commit": "cz"
},
- 使用
git add . npm run commit
代碼送出驗證
如果我們按照cz來規範了送出風格,但是依然有同僚通過
git commit
按照不規範的格式送出應該怎麼辦呢?
我們可以通過
commitlint
來限制送出;
1.安裝
@commitlint/config-conventional
和
@commitlint/cli
2.在根目錄建立commitlint.config.js檔案,配置commitlint
module.exports = {
extends: ['@commitlint/config-conventional']
}
3.使用husky生成commit-msg檔案,驗證送出資訊:
內建axios
- 安裝
yarn add axios
- 封裝axios
在src檔案夾下,建立檔案夾
serve/request
在
request
裡建立
type.ts
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
export interface HYRequestInterceptors<T = AxiosResponse> {
requestInterceptor?: (config: AxiosRequestConfig) => AxiosRequestConfig
requestInterceptorCatch?: (error: any) => any
responseInterceptor?: (res: T) => T
responseInterceptorCatch?: (error: any) => any
}
export interface HYRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {
interceptors?: HYRequestInterceptors<T>
showLoading?: boolean
}
在
request
裡建立
index.ts
import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { HYRequestInterceptors, HYRequestConfig } from './type'
import { ElLoading } from 'element-plus'
import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading.js'
const DEAFULT_LOADING = true
class HYRequest {
instance: AxiosInstance
interceptors?: HYRequestInterceptors
showLoading: boolean
loading?: LoadingInstance
constructor(config: HYRequestConfig) {
// 建立axios執行個體
this.instance = axios.create(config)
// 儲存基本資訊
this.showLoading = config.showLoading ?? DEAFULT_LOADING
this.interceptors = config.interceptors
// 使用攔截器
this.instance.interceptors.request.use(
this.interceptors?.requestInterceptor,
this.interceptors?.requestInterceptorCatch
)
this.instance.interceptors.response.use(
this.interceptors?.responseInterceptor,
this.interceptors?.responseInterceptorCatch
)
//添加所有的執行個體都有的攔截器
this.instance.interceptors.request.use(
(config) => {
console.log('所有的執行個體都有的攔截器: 請求成功攔截')
if (this.showLoading) {
this.loading = ElLoading.service({
lock: true,
text: '正在請求資料....',
background: 'rgba(0, 0, 0, 0.5)'
})
}
return config
},
(err) => {
console.log('所有的執行個體都有的攔截器: 請求失敗攔截')
return err
}
)
this.instance.interceptors.response.use(
(res) => {
console.log('所有的執行個體都有的攔截器: 響應成功攔截')
//移除加載
this.loading?.close()
const data = res.data
return data
},
(err) => {
this.loading?.close()
if (err.response.status === 404) {
console.log('404的錯誤~')
}
return err
}
)
}
request<T>(config: HYRequestConfig<T>): Promise<T> {
return new Promise((resolve, reject) => {
// 1.單個請求對請求config的處理
if (config.interceptors?.requestInterceptor) {
config = config.interceptors.requestInterceptor(config)
}
// 2.判斷是否需要顯示loading
if (config.showLoading === false) {
this.showLoading = config.showLoading
}
this.instance
.request<any, T>(config)
.then((res) => {
// 1.單個請求對資料的處理
if (config.interceptors?.responseInterceptor) {
res = config.interceptors.responseInterceptor(res)
}
// 2.将showLoading設定true, 這樣不會影響下一個請求
this.showLoading = DEAFULT_LOADING
// 3.将結果resolve傳回出去
resolve(res)
})
.catch((err) => {
// 将showLoading設定true, 這樣不會影響下一個請求
this.showLoading = DEAFULT_LOADING
reject(err)
return err
})
})
}
get<T>(config: HYRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'GET' })
}
post<T>(config: HYRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'POST' })
}
delete<T>(config: HYRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'DELETE' })
}
patch<T>(config: HYRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'PATCH' })
}
}
export default HYRequest
在根目錄建立
.env.development
,
.env.production
,
.env.test
建立
.env.development
VUE_APP_BASE_URL=https://coderwhy.org/dev
VUE_APP_BASE_NAME=coderwhy
建立
.env.production
VUE_APP_BASE_URL=https://coderwhy.org/prod
VUE_APP_BASE_NAME=kobe
建立
.env.test
VUE_APP_BASE_URL=https://coderwhy.org/test
VUE_APP_BASE_NAME=james
在
request
裡建立config.ts
let BASE_URL = ''
const TIME_OUT = 10000
if (process.env.NODE_ENV === 'development') {
BASE_URL = '/api'
} else if (process.env.NODE_ENV === 'production') {
BASE_URL = 'http://coderwhy.org/prod'
} else {
BASE_URL = 'http://coderwhy.org/test'
}
export { BASE_URL, TIME_OUT }
在
src
目錄下建立
utils
檔案夾并在裡面建立
cache.ts
目的:封裝
localStorage
class LocalCache {
setCache(key: string, value: any) {
window.localStorage.setItem(key, JSON.stringify(value))
}
getCache(key: string) {
// obj => string => obj
const value = window.localStorage.getItem(key)
if (value) {
return JSON.parse(value)
}
}
deleteCache(key: string) {
window.localStorage.removeItem(key)
}
clearCache() {
window.localStorage.clear()
}
}
export default new LocalCache()
在
service
下建立
index.ts
// service統一出口
import HYRequest from './request'
import { BASE_URL, TIME_OUT } from './request/config'
import localCache from '@/utils/cache'
const hyRequest = new HYRequest({
baseURL: BASE_URL,
timeout: TIME_OUT,
interceptors: {
requestInterceptor: (config) => {
// 攜帶token的攔截
const token = localCache.getCache('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
requestInterceptorCatch: (err) => {
return err
},
responseInterceptor: (res) => {
return res
},
responseInterceptorCatch: (err) => {
return err
}
}
})
export default hyRequest
在vue.config.js配置跨域
module.exports = defineConfig({
transpileDependencies: true,
outputDir: './build',
devServer: {
proxy: {
'^/api': {
target: 'http://152.136.185.210:5000',
pathRewrite: {
'^/api': ''
},
changeOrigin: true
}
}
},
...
});
測試封裝是否成功
import hyRequest from './service/index'
hyRequest
.request({
url: '/login',
method: 'POST',
data: {
name: 'coderwhy',
password: '123456'
}
})
.then((res) => console.log(res))