目錄
- 一. 代碼規範
- 1.1. 內建 editorconfig 配置
- 1.2. 使用 prettier 工具
- 1.3. 使用 ESLint 檢測
- 1.4. git Husky 和 eslint
- 1.5. git commit 規範
- 1.5.1. 代碼送出風格
- 1.5.2. 代碼送出驗證
- 二. 第三方庫內建
- 2.1. vue.config.js 配置
- 2.2. vue-router 內建
- 2.3. vuex 內建
- 2.4. element-plus 內建
- 2.4.1. 全局引入
- 2.4.2. 局部引入
- 2.5. axios 內建
- 2.6. VSCode 配置
- 2.7. css 初始化
一. 代碼規範
1.1. 內建 editorconfig 配置
EditorConfig 有助于為不同 IDE 編輯器上處理同一項目的多個開發人員維護一緻的編碼風格。
# http://editorconfig.org
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
VSCode 需要安裝一個插件:EditorConfig for VS Code
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZwpmLi12ZnVDMqBHMzoWe5gTOodmMxN3Zxk3ZOt2czkGOwAzLcV2ZyFGbvwlbj5yZtlWYul2cuETY2R3Lc9CX6MHc0RHaiojIsJye.jpg)
1.2. 使用 prettier 工具
Prettier 是一款強大的代碼格式化工具,支援 JavaScript、TypeScript、CSS、SCSS、Less、JSX、Angular、Vue、GraphQL、JSON、Markdown 等語言,基本上前端能用到的檔案格式它都可以搞定,是當下最流行的代碼格式化工具。
1.安裝 prettier
npm install prettier -D
2.配置.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
}
3.建立.prettierignore 忽略檔案
/dist/*
.local
.output.js
/node_modules/**
**/*.svg
**/*.sh
/public/*
4.VSCode 需要安裝 prettier 的插件
5.測試 prettier 是否生效
- 測試一:在代碼中儲存代碼;
- 測試二:配置一次性修改的指令;
在 package.json 中配置一個 scripts:
"prettier": "prettier --write ."
1.3. 使用 ESLint 檢測
1.在前面建立項目的時候,我們就選擇了 ESLint,是以 Vue 會預設幫助我們配置需要的 ESLint 環境。
2.VSCode 需要安裝 ESLint 插件:
3.解決 eslint 和 prettier 沖突的問題:
安裝插件:(vue 在建立項目時,如果選擇 prettier,那麼這兩個插件會自動安裝)
npm i eslint-plugin-prettier eslint-config-prettier -D
添加 prettier 插件:
extends: [
"plugin:vue/vue3-essential",
"eslint:recommended",
"@vue/typescript/recommended",
"@vue/prettier",
"@vue/prettier/@typescript-eslint",
'plugin:prettier/recommended'
],
1.4. git Husky 和 eslint
雖然我們已經要求項目使用 eslint 了,但是不能保證組員送出代碼之前都将 eslint 中的問題解決掉了:
- 也就是我們希望保證代碼倉庫中的代碼都是符合 eslint 規範的;
- 那麼我們需要在組員執行
指令的時候對其進行校驗,如果不符合 eslint 規範,那麼自動通過規範進行修複;git commit
那麼如何做到這一點呢?可以通過 Husky 工具:
- husky 是一個 git hook 工具,可以幫助我們觸發 git 送出的各個階段:pre-commit、commit-msg、pre-push
如何使用 husky 呢?
這裡我們可以使用自動配置指令:
ios:
npx husky-init && npm install
win10:
npx husky-init "&&" npm install
npx husky-init ; npm install
這裡會做三件事:
1.安裝 husky 相關的依賴:
2.在項目目錄下建立
.husky
檔案夾:
npx huksy install
3.在 package.json 中添加一個腳本:
接下來,我們需要去完成一個操作:在進行 commit 時,執行 lint 腳本:
這個時候我們執行 git commit 的時候會自動對代碼進行 lint 校驗。
1.5. git commit 規範
1.5.1. 代碼送出風格
通常我們的 git commit 會按照統一的風格來送出,這樣可以快速定位每次送出的内容,友善之後對版本進行控制。
但是如果每次手動來編寫這些是比較麻煩的事情,我們可以使用一個工具:Commitizen
-
Commitizen 是一個幫助我們編寫規範 commit message 的工具;
1.安裝 Commitizen
npm install commitizen -D
2.安裝 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 | 代碼回退 |
- 第二步選擇本次修改的範圍(作用域)
- 第三步選擇送出的資訊
- 第四步送出詳細的描述資訊
- 第五步是否是一次重大的更改
- 第六步是否影響某個 open issue
我們也可以在 scripts 中建構一個指令來執行 cz:
1.5.2. 代碼送出驗證
如果我們按照 cz 來規範了送出風格,但是依然有同僚通過
git commit
按照不規範的格式送出應該怎麼辦呢?
-
我們可以通過 commitlint 來限制送出;
1.安裝 @commitlint/config-conventional 和 @commitlint/cli
npm i @commitlint/config-conventional @commitlint/cli -D
2.在根目錄建立 commitlint.config.js 檔案,配置 commitlint
module.exports = {
extends: ['@commitlint/config-conventional']
}
3.使用 husky 生成 commit-msg 檔案,驗證送出資訊:
npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"
二. 第三方庫內建
2.1. vue.config.js 配置
vue.config.js 有三種配置方式:
- 方式一:直接通過 CLI 提供給我們的選項來配置:
- 比如 publicPath:配置應用程式部署的子目錄(預設是
,相當于部署在/
);https://www.my-app.com/
- 比如 outputDir:修改輸出的檔案夾;
- 比如 publicPath:配置應用程式部署的子目錄(預設是
- 方式二:通過 configureWebpack 修改 webpack 的配置:
- 可以是一個對象,直接會被合并;
- 可以是一個函數,會接收一個 config,可以通過 config 來修改配置;
- 方式三:通過 chainWebpack 修改 webpack 的配置:
- 是一個函數,會接收一個基于 webpack-chain 的 config 對象,可以對配置進行修改;
const path = require('path')
module.exports = {
outputDir: './build',
// configureWebpack: {
// resolve: {
// alias: {
// views: '@/views'
// }
// }
// }
// configureWebpack: (config) => {
// config.resolve.alias = {
// '@': path.resolve(__dirname, 'src'),
// views: '@/views'
// }
// },
chainWebpack: (config) => {
config.resolve.alias
.set('@', path.resolve(__dirname, 'src'))
.set('views', '@/views')
}
}
2.2. vue-router 內建
安裝 vue-router 的最新版本:
npm install vue-router@next
建立 router 對象:
import { createRouter, createWebHashHistory } from 'vue-router'
import { RouteRecordRaw } from 'vue-router'
const routes: RouteRecordRaw[] = [
{
path: '/',
redirect: '/main'
},
{
path: '/main',
component: () => import('../views/main/main.vue')
},
{
path: '/login',
component: () => import('../views/login/login.vue')
}
]
const router = createRouter({
routes,
history: createWebHashHistory()
})
export default router
安裝 router:
import router from './router'
createApp(App).use(router).mount('#app')
在 App.vue 中配置跳轉:
<template>
<div id="app">
<router-link to="/login">登入</router-link>
<router-link to="/main">首頁</router-link>
<router-view></router-view>
</div>
</template>
2.3. vuex 內建
安裝 vuex:
npm install vuex@next
建立 store 對象:
import { createStore } from 'vuex'
const store = createStore({
state() {
return {
name: 'coderwhy'
}
}
})
export default store
安裝 store:
createApp(App).use(router).use(store).mount('#app')
在 App.vue 中使用:
<h2>{{ $store.state.name }}</h2>
2.4. element-plus 內建
Element Plus,一套為開發者、設計師和産品經理準備的基于 Vue 3.0 的桌面端元件庫:
- 相信很多同學在 Vue2 中都使用過 element-ui,而 element-plus 正是 element-ui 針對于 vue3 開發的一個 UI 元件庫;
- 它的使用方式和很多其他的元件庫是一樣的,是以學會 element-plus,其他類似于 ant-design-vue、NaiveUI、VantUI 都是差不多的;
安裝 element-plus
npm install element-plus
2.4.1. 全局引入
一種引入 element-plus 的方式是全局引入,代表的含義是所有的元件和插件都會被自動注冊:
import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'
import router from './router'
import store from './store'
createApp(App).use(router).use(store).use(ElementPlus).mount('#app')
2.4.2. 局部引入
也就是在開發中用到某個元件對某個元件進行引入:
<template>
<div id="app">
<router-link to="/login">登入</router-link>
<router-link to="/main">首頁</router-link>
<router-view></router-view>
<h2>{{ $store.state.name }}</h2>
<el-button>預設按鈕</el-button>
<el-button type="primary">主要按鈕</el-button>
<el-button type="success">成功按鈕</el-button>
<el-button type="info">資訊按鈕</el-button>
<el-button type="warning">警告按鈕</el-button>
<el-button type="danger">危險按鈕</el-button>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { ElButton } from 'element-plus'
export default defineComponent({
name: 'App',
components: {
ElButton
}
})
</script>
<style lang="less"></style>
但是我們會發現是沒有對應的樣式的,引入樣式有兩種方式:
- 全局引用樣式(像之前做的那樣);
-
局部引用樣式(通過 babel 的插件);
1.安裝 babel 的插件:
npm install babel-plugin-import -D
2.配置 babel.config.js
module.exports = {
plugins: [
[
'import',
{
libraryName: 'element-plus',
customStyleName: (name) => {
return `element-plus/lib/theme-chalk/${name}.css`
}
}
]
],
presets: ['@vue/cli-plugin-babel/preset']
}
但是這裡依然有個弊端:
- 這些元件我們在多個頁面或者元件中使用的時候,都需要導入并且在 components 中進行注冊;
- 是以我們可以将它們在全局注冊一次;
import {
ElButton,
ElTable,
ElAlert,
ElAside,
ElAutocomplete,
ElAvatar,
ElBacktop,
ElBadge
} from 'element-plus'
const app = createApp(App)
const components = [
ElButton,
ElTable,
ElAlert,
ElAside,
ElAutocomplete,
ElAvatar,
ElBacktop,
ElBadge
]
for (const cpn of components) {
app.component(cpn.name, cpn)
}
2.5. axios 內建
安裝 axios:
npm install axios
封裝 axios:
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { Result } from './types'
import { useUserStore } from '/@/store/modules/user'
class HYRequest {
private instance: AxiosInstance
private readonly options: AxiosRequestConfig
constructor(options: AxiosRequestConfig) {
this.options = options
this.instance = axios.create(options)
this.instance.interceptors.request.use(
(config) => {
const token = useUserStore().getToken
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(err) => {
return err
}
)
this.instance.interceptors.response.use(
(res) => {
// 攔截響應的資料
if (res.data.code === 0) {
return res.data.data
}
return res.data
},
(err) => {
return err
}
)
}
request<T = any>(config: AxiosRequestConfig): Promise<T> {
return new Promise((resolve, reject) => {
this.instance
.request<any, AxiosResponse<Result<T>>>(config)
.then((res) => {
resolve(res as unknown as Promise<T>)
})
.catch((err) => {
reject(err)
})
})
}
get<T = any>(config: AxiosRequestConfig): Promise<T> {
return this.request({ ...config, method: 'GET' })
}
post<T = any>(config: AxiosRequestConfig): Promise<T> {
return this.request({ ...config, method: 'POST' })
}
patch<T = any>(config: AxiosRequestConfig): Promise<T> {
return this.request({ ...config, method: 'PATCH' })
}
delete<T = any>(config: AxiosRequestConfig): Promise<T> {
return this.request({ ...config, method: 'DELETE' })
}
}
export default HYRequest
2.6. VSCode 配置
{
"workbench.iconTheme": "vscode-great-icons",
"editor.fontSize": 17,
"eslint.migration.2_x": "off",
"[javascript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"files.autoSave": "afterDelay",
"editor.tabSize": 2,
"terminal.integrated.fontSize": 16,
"editor.renderWhitespace": "all",
"editor.quickSuggestions": {
"strings": true
},
"debug.console.fontSize": 15,
"window.zoomLevel": 1,
"emmet.includeLanguages": {
"javascript": "javascriptreact"
},
"explorer.confirmDragAndDrop": false,
"workbench.tree.indent": 16,
"javascript.updateImportsOnFileMove.enabled": "always",
"editor.wordWrap": "on",
"path-intellisense.mappings": {
"@": "${workspaceRoot}/src"
},
"hediet.vscode-drawio.local-storage": "eyIuZHJhd2lvLWNvbmZpZyI6IntcImxhbmd1YWdlXCI6XCJcIixcImN1c3RvbUZvbnRzXCI6W10sXCJsaWJyYXJpZXNcIjpcImdlbmVyYWw7YmFzaWM7YXJyb3dzMjtmbG93Y2hhcnQ7ZXI7c2l0ZW1hcDt1bWw7YnBtbjt3ZWJpY29uc1wiLFwiY3VzdG9tTGlicmFyaWVzXCI6W1wiTC5zY3JhdGNocGFkXCJdLFwicGx1Z2luc1wiOltdLFwicmVjZW50Q29sb3JzXCI6W1wiRkYwMDAwXCIsXCIwMENDNjZcIixcIm5vbmVcIixcIkNDRTVGRlwiLFwiNTI1MjUyXCIsXCJGRjMzMzNcIixcIjMzMzMzM1wiLFwiMzMwMDAwXCIsXCIwMENDQ0NcIixcIkZGNjZCM1wiLFwiRkZGRkZGMDBcIl0sXCJmb3JtYXRXaWR0aFwiOjI0MCxcImNyZWF0ZVRhcmdldFwiOmZhbHNlLFwicGFnZUZvcm1hdFwiOntcInhcIjowLFwieVwiOjAsXCJ3aWR0aFwiOjExNjksXCJoZWlnaHRcIjoxNjU0fSxcInNlYXJjaFwiOnRydWUsXCJzaG93U3RhcnRTY3JlZW5cIjp0cnVlLFwiZ3JpZENvbG9yXCI6XCIjZDBkMGQwXCIsXCJkYXJrR3JpZENvbG9yXCI6XCIjNmU2ZTZlXCIsXCJhdXRvc2F2ZVwiOnRydWUsXCJyZXNpemVJbWFnZXNcIjpudWxsLFwib3BlbkNvdW50ZXJcIjowLFwidmVyc2lvblwiOjE4LFwidW5pdFwiOjEsXCJpc1J1bGVyT25cIjpmYWxzZSxcInVpXCI6XCJcIn0ifQ==",
"hediet.vscode-drawio.theme": "Kennedy",
"editor.fontFamily": "Source Code Pro, 'Courier New', monospace",
"editor.smoothScrolling": true,
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"workbench.colorTheme": "Atom One Dark",
"vetur.completion.autoImport": false,
"security.workspace.trust.untrustedFiles": "open",
"eslint.lintTask.enable": true,
"eslint.alwaysShowStatus": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
2.7. css 初始化
安裝
normalize.css
npm install normalize.css
編寫基礎 css 格式化代碼
body {
padding: 0;
margin: 0;
}
html,
body,
#app {
100%;
height: 100%;
}
統一導入 main.ts
import 'normalize.css'
import '@/assets/css/index.less'