一. 項目創建
1. 搭建步驟
(1). 輸入指令【vue create vue3_cms01】,創建項目,進行如下選擇。
(2). 選擇項目包含的內容,如下圖所示,babel、ts、vue-router、vuex、css處理器、Linter都集成進去。
(3). 對集成進去的類庫進行選擇,如下圖:
(4). 創建成功,項目目錄如下:
(5). 運行指令【npm run serve】,然后訪問地址: http://localhost:8080/
2. vue-router測試
在src/router/index.ts,進行相關配置,默認導入的代碼如下

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'; import Home from '../views/Home.vue'; const routes: Array<RouteRecordRaw> = [ { path: '/', name: 'Home', component: Home, }, { path: '/about', name: 'About', component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'), }, ]; const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes, }); export default router;
引用代碼如下:
import { createApp } from 'vue'; import App from './App.vue'; import router from './router'; import store from './store'; const app = createApp(App); app.use(router); //引入vue-router插件 app.use(store); //引入vuex插件 app.mount('#app');
3. vuex測試
在src/store/index.ts,進行相關配置,默認導入代碼如下

import { createStore } from 'vuex'; export default createStore({ state: {}, mutations: {}, actions: {}, modules: {}, });
引用代碼如下:
import { createApp } from 'vue'; import App from './App.vue'; import router from './router'; import store from './store'; const app = createApp(App); app.use(router); //引入vue-router插件 app.use(store); //引入vuex插件 app.mount('#app');
二. 代碼規范配置
1. 集成editorconfig配置
(1). editorConfig 有助於為不同 IDE 編輯器上處理同一項目的多個開發人員維護一致的編碼風格。 在項目的根目錄下新建 .editorconfig 文件,內容如下:
官網: http://editorconfig.org
# 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
(2). 安裝vscode的相關插件
EditorConfig for VS Code
2. 使用prettier工具
Prettier 是一款強大的代碼格式化工具,支持 JavaScript、TypeScript、CSS、SCSS、Less、JSX、Angular、Vue、GraphQL、JSON、Markdown 等語言,基本上前端能用到的文件格式它都可以搞定,是當下最流行的代碼格式化工具。
詳見官網:https://www.prettier.cn/
(1). 基於項目依賴進行安裝,運行指令【npm install prettier -D】
(2). 根目錄下新建文件 .prettierrc,格式為json格式,代碼如下:
{ "useTabs": true, "tabWidth": 2, "printWidth": 80, "singleQuote": true, "trailingComma": "all", "semi": true, "vueIndentScriptAndStyle": true }
注意: 這種格式有個問題,就是不能寫注釋!!!!
含義剖析:
-
-
tabWidth:tab是空格的情況下,是幾個空格,選擇2個;
-
printWidth:當行字符的長度,推薦80,也有人喜歡100或者120;
-
singleQuote:使用單引號還是雙引號,選擇true,使用單引號;
-
trailingComma:在多行輸入的尾逗號是否添加,不需要添加設置為
none
,需要添加設置為 all; -
semi:語句末尾是否要加分號,默認值true,選擇false表示不加;
-
vueIndentScriptAndStyle: 表示.vue文件中,<script>和<style>
推薦:由於.prettierrc不能寫注釋,這里推薦使用 .prettierrc.js,通過module.export進行導出,就可以盡情的寫注釋了
module.exports = { //使用tab縮進還是空格縮進,false表示空格縮進; useTabs: true, //tab是空格的情況下,是幾個空格,選擇2個; tabWidth: 2, //當行字符的長度,推薦80,也有人喜歡100或者120; printWidth: 80, //使用單引號還是雙引號,選擇true,使用單引號; singleQuote: true, //在多行輸入的尾逗號是否添加,不需要添加設置為 `none`,需要添加設置為 all; trailingComma: 'all', //語句末尾是否要加分號,默認值true,選擇false表示不加; semi: true, //表示.vue文件中,<script>和<style>標簽中的代碼縮進兩個單元格 vueIndentScriptAndStyle: true, };
(3). 忽略文件配置,新建 .prettierignore,里面的內容不進行prettierrc格式配置
/dist/* .local .output.js /node_modules/** **/*.svg **/*.sh /public/*
(4). VSCode插件配置
Prettier - Code formatter
安裝完以后,執行格式化快捷鍵【ctrl+k+d】,當前頁面的就格式化了,如果想【ctrl+s】的時候進行格式化,需要在設置里勾選Format On Save。
(5). 通過指令進行全局修復
運行指令【npx prettier --write .】,可以進行全局格式修復,不含忽略文件中的內容
或者在package.json中進行如下配置,然后運行指令 【npm run prettier】進行全局格式修復,原理同上
"scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint", "prettier": "prettier --write ." },
3. 使用ESLint檢測
在前面創建項目的時候,我們就選擇了ESLint,所以Vue會默認幫助我們配置需要的ESLint環境,主要用於檢查代碼格式是否准確。
常用配置查詢:
http://eslint.cn/docs/rules/
https://eslint.vuejs.org/rules/
(1). 安裝vscode插件
ESLint
(2). 解決eslint和prettier沖突的問題
A. 運行指令【npm i eslint-plugin-prettier eslint-config-prettier -D】進行安裝
B. 在.eslintrc.js進行如下配置
module.exports = { root: true, env: { node: true, }, extends: [ 'plugin:vue/vue3-essential', 'eslint:recommended', '@vue/typescript/recommended', '@vue/prettier', '@vue/prettier/@typescript-eslint', // 處理eslint和prettier的沖突問題 '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', // 關閉vueIndentScriptAndStyle在.vue文件中的格式驗證 forceConsistentCasingInFileNames: 'off', }, };
(3). eslint的忽略文件
.eslintignore 內容如下:
*.sh node_modules lib *.md *.scss *.woff *.ttf .vscode .idea dist mock public bin build config index.html src/assets
4. .browserslistrc
主要是用來配置瀏覽器兼容性的,詳見:https://cli.vuejs.org/zh/guide/browser-compatibility.html https://github.com/browserslist/browserslist
下面文件的含義:市場份額大於1%的瀏覽器,最新兩個版本,正在維護的瀏覽器
> 1% last 2 versions not dead
5. tsconfig.json
(詳細配置見:https://www.typescriptlang.org/tsconfig)
tsconfig.json

{ "compilerOptions": { // 目標代碼(ts -> js(es5/6/7)) "target": "esnext", // 目標代碼需要使用的模塊化方案(commonjs require/module.exports/ esmodule import/export) "module": "esnext", // 一些嚴格的檢查(如:any) "strict": false, // 不進行any語法檢查 "noImplicitAny": false, // 對jsx進行怎么樣的處理 "jsx": "preserve", // 輔助的導入功能 "importHelpers": true, // 按照node的方式去解析模塊 import "/index.node" "moduleResolution": "node", // 跳過一些庫的類型檢測 (axios -> 類型/ lodash -> @types/lodash / 其他的第三方) // import { Person } from 'axios' "skipLibCheck": true, // export default/module.exports = {} //表示允許同時使用: es module 和 commonjs "esModuleInterop": true, "allowSyntheticDefaultImports": true, // 要不要生成映射文件(ts -> js) "sourceMap": true, // 文件路徑在解析時, 基本url "baseUrl": ".", // 指定具體要解析使用的類型 "types": ["webpack-env"], // 路徑解析(類似於webpack alias) "paths": { "@/*": ["src/*"], "components/*": ["src/components/*"] }, // 可以指定在項目中可以使用哪里庫的類型(Proxy/Window/Document) "lib": ["esnext", "dom", "dom.iterable", "scripthost"], // 允許在<script>中寫純js代碼 "allowJs": true }, "include": ["src/**/*.js", "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "tests/**/*.ts", "tests/**/*.tsx"], "exclude": ["node_modules"] }
補充:ts項目中允許js代碼,需要修改以下幾個位置
6. 配置git Husky
(1). 說明
husky是一個git hook工具,可以幫助我們觸發git提交的各個階段:pre-commit、commit-msg、pre-push,它的作用是 git commit的時候,把所有代碼都按照eslint的規范進行自動修正一下,然后再提交。
(2). 步驟
A. 運行指令【npx husky-init && npm install】 或者 powershell中 【npx husky-init '&&' npm install】
自動做了以下3件事:
B. 在.husky文件夾下的pre-commit中,將里面的指令改為 【npm run lint】
#!/bin/sh . "$(dirname "$0")/_/husky.sh" npm run lint
C. 當運行 git commit提交指令的時候,會先執行一下代碼規范調整。
!
- 作 者 : Yaopengfei(姚鵬飛)
- 博客地址 : http://www.cnblogs.com/yaopengfei/
- 聲 明1 : 如有錯誤,歡迎討論,請勿謾罵^_^。
- 聲 明2 : 原創博客請在轉載時保留原文鏈接或在文章開頭加上本人博客地址,否則保留追究法律責任的權利。