vue3 admin 保姆教學指南 | 項目規範集成教程,看完秒懂項目中各種奇怪的文件和配置

語言: CN / TW / HK

一個項目要有統一的規範,需要使用eslint+stylelint+prettier來對我們代碼質量做檢測和修復,需要使用husky來做commit攔截,需要使用commitlint來統一提交規範,需要使用preinstall來統一包管理工具。本文教大家怎麼一步一步來集成自己的項目規範。

環境準備

  • node v16.17.0
  • pnpm 7.11.0

項目初始化

本項目使用vite進行構建,vite官方中文文檔參考:cn.vitejs.dev/guide/

項目初始化命令

pnpm create vite

我們這裏選擇使用vue+typescript的方式進行初始化。

Project name命名為guigu-sph-mall-admin,意為尚品彙商城管理系統

初始化完成以後進入guiug-sph-mall目錄,安裝依賴pnpm install,然後運行項目pnpm run dev,在瀏覽器打開http://localhost:5173/,即可看到預覽效果:

配置eslint和prettier

1.eslint驗證代碼是否符合定義的規範

需要安裝以下插件

  • eslint-plugin-vue:vue.js的Eslint插件(查找vue語法錯誤,發現錯誤指令,查找違規風格指南)
  • eslint-plugin-prettier:運行更漂亮的Eslint,使prettier規則優先級更高,Eslint優先級低
  • eslint-config-prettier:讓所有與prettier規則存在衝突的Eslint rules失效,並使用prettier進行代碼檢查
  • @babel/eslint-parser:該解析器允許使用Eslint校驗所有babel code

首先安裝eslint

pnpm i -D eslint

生成配置文件

// 生成配置文件,.eslintrc.js npx eslint --init

配置項如下圖所示

再安裝下面的依賴

pnpm install -D eslint-plugin-import eslint-plugin-vue eslint-plugin-node eslint-plugin-prettier eslint-config-prettier @babel/eslint-parser

修改配置文件如下

module.exports = { env: { browser: true, es2021: true, node: true, jest: true, }, extends: [ 'eslint:recommended', 'plugin:vue/vue3-essential', 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended', ], overrides: [], parser: 'vue-eslint-parser', parserOptions: { ecmaVersion: 'latest', sourceType: 'module', parser: '@typescript-eslint/parser', }, plugins: ['vue', '@typescript-eslint'], rules: { 'space-before-function-paren': ['error', 'never'], semi: 0, // 結尾不要分號 }, }

配置.eslintignore, 防止校驗打包的產物

// .eslintignore 配置, 防止校驗打包的產物 dist node_modules

在package.json 中添加運行腳本

"scripts": { "lint": "eslint src", "fix": "eslint src --fix", }

2.pretter格式化代碼符合定義的規範

安裝包

pnpm install -D eslint-plugin-prettier prettier eslint-config-prettier

.prettierrc.json添加如下規則:

// .prettierrc.json { "singleQuote": true, "semi": false, "bracketSpacing": true, "htmlWhitespaceSensitivity": "ignore", "endOfLine": "auto", "trailingComma": "all", "tabWidth": 2 }

測試一下代碼檢查是否生效了,我們在main.ts中修改成如下內容

可以看到代碼已經紅了,然後運行npm run lint來檢查一下代碼不規範原因

可以看到這裏有兩處錯誤,運行npm run fix修改這個錯誤

這樣就符合我們定義的代碼規範了。

到此,我們的eslint和prettier配置完畢。

如果出現下面報錯,卸載vetur插件,安裝TypeScript Vue Plugin (Volar)、Vue Language Features (Volar)插件即可。

配置stylelint

stylelint為css的lint工具。可格式化css代碼,檢查css語法錯誤與不合理的寫法,指定css書寫順序等。

安裝依賴

我們的項目中使用less作為預處理器,安裝以下依賴:

pnpm add stylelint postcss postcss-less postcss-html stylelint-config-prettier stylelint-config-recommended-less stylelint-config-standard stylelint-config-standard-vue stylelint-less stylelint-order -D

依賴説明

增加 .stylelintrc 配置文件

{ "extends": [ "stylelint-config-standard", "stylelint-config-prettier", "stylelint-config-recommended-less", "stylelint-config-standard-vue" ], "plugins": ["stylelint-order"], "overrides": [ { "files": ["**/*.(less|css|vue|html)"], "customSyntax": "postcss-less" }, { "files": ["**/*.(html|vue)"], "customSyntax": "postcss-html" } ], "ignoreFiles": [ "**/*.js", "**/*.jsx", "**/*.tsx", "**/*.ts", "**/*.json", "**/*.md", "**/*.yaml" ], "rules": { "no-descending-specificity": null, "selector-pseudo-element-no-unknown": [ true, { "ignorePseudoElements": ["v-deep"] } ], "selector-pseudo-class-no-unknown": [ true, { "ignorePseudoClasses": ["deep"] } ], "order/properties-order": [ "position", "top", "right", "bottom", "left", "z-index", "display", "justify-content", "align-items", "float", "clear", "overflow", "overflow-x", "overflow-y", "padding", "padding-top", "padding-right", "padding-bottom", "padding-left", "margin", "margin-top", "margin-right", "margin-bottom", "margin-left", "width", "min-width", "max-width", "height", "min-height", "max-height", "font-size", "font-family", "text-align", "text-justify", "text-indent", "text-overflow", "text-decoration", "white-space", "color", "background", "background-position", "background-repeat", "background-size", "background-color", "background-clip", "border", "border-style", "border-width", "border-color", "border-top-style", "border-top-width", "border-top-color", "border-right-style", "border-right-width", "border-right-color", "border-bottom-style", "border-bottom-width", "border-bottom-color", "border-left-style", "border-left-width", "border-left-color", "border-radius", "opacity", "filter", "list-style", "outline", "visibility", "box-shadow", "text-shadow", "resize", "transition" ] } }

配置命令

"scripts": { "lint:style": "stylelint src/**/*.{css,less,vue} --cache --fix" }

最後配置統一的prettier來格式化我們的js和css,html代碼

"scripts": { "dev": "vite", "build": "vue-tsc && vite build", "preview": "vite preview", "lint": "eslint src", "fix": "eslint src --fix", "format": "prettier --write "./**/*.{html,vue,ts,js,json,md}"", "lint:eslint": "eslint src/**/*.{ts,vue} --cache --fix", "lint:style": "stylelint src/**/*.{css,less,vue} --cache --fix" },

當我們運行pnpm format的時候,會把代碼直接格式化

vscode保存文件自動修復代碼

實現每次保存代碼時,自動執行lint命令來修復代碼的錯誤。這個操作需要依賴eslint插件來完成,需要提前在vscode插件市場安裝好eslint。然後有兩種方式可以配置:

第一種:

直接在項目的跟路徑創建.vscode/settings.json文件,然後在其中加入以下配置。

{ // 開啟自動修復 "editor.codeActionsOnSave": { "source.fixAll": false, "source.fixAll.eslint": true } }

第二種:

用shift+cmd+p,打開搜索命令框,輸入settings,選擇下面這個

這個文件是vscode的系統配置文件,直接把

// 開啟自動修復 "editor.codeActionsOnSave": { "source.fixAll": false, "source.fixAll.eslint": true }

這段代碼複製進去,任何項目打開,都會自動保存文件了。

這裏為了讓別的人也能方便的使用,我們的項目中直接採用第一種方式。

下面是完整的配置:

{ // 開啟自動修復 "editor.codeActionsOnSave": { "source.fixAll": false, "source.fixAll.eslint": true, "source.fixAll.stylelint": true }, // 保存的時候自動格式化 "editor.formatOnSave": true, // 默認格式化工具選擇prettier "editor.defaultFormatter": "esbenp.prettier-vscode", // 配置該項,新建文件時默認就是space:2 "editor.tabSize": 2, // stylelint校驗的文件格式 "stylelint.validate": ["css", "less", "vue", "html"] }

配置husky

在上面我們已經集成好了我們代碼校驗工具,但是需要每次手動的去執行命令才會格式化我們的代碼。如果有人沒有格式化就提交了,那這個規範就沒什麼用。所以我們強制讓開發人員按照代碼規範來提交。

要做到這件事情,可以利用husky來在代碼提交之前出發git hook,然後執行pnpm format來自動的格式化我們的代碼。

安裝husky

pnpm install -D husky

執行

npx husky-init

會在根目錄下生成個一個.husky目錄,在這個目錄下面會有一個pre-commit文件,這個文件裏面的命令在我們執行commit的時候就會執行

安裝lint-staged

pnpm install -D lint-staged

配置命令

{ "scripts": { "lint-staged": "lint-staged" }, "lint-staged": { "**/*.{js,jsx,ts,tsx,vue}": [ "prettier --write", "eslint --fix", "stylelint --fix", "git add" ] }, }

在pre-commit文件添加命令

```

!/usr/bin/env sh

. "$(dirname -- "$0")/_/husky.sh"

pnpm lint-staged ```

當我們對代碼進行commit操作的時候,就會執行命令,對代碼進行格式化,然後再提交。

配置commitlint校驗提交信息

對於我們的commit信息,也是有你統一規範的,不能隨便寫,比如下面的:

要讓每個人都按照統一的標準來執行,我們可以利用commitlint來實現。

安裝包

pnpm add @commitlint/config-conventional @commitlint/cli -D

添加配置文件,新建commitlint.config.cjs(注意是cjs),然後添加下面的代碼:

module.exports = { extends: ['@commitlint/config-conventional'], // 校驗規則 rules: { 'type-enum': [ 2, 'always', [ 'feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'chore', 'revert', 'build', ], ], 'type-case': [0], 'type-empty': [0], 'scope-empty': [0], 'scope-case': [0], 'subject-full-stop': [0, 'never'], 'subject-case': [0, 'never'], 'header-max-length': [0, 'always', 72], }, }

配置scripts

```

在scrips中添加下面的代碼

{ "scripts": { "commitlint": "commitlint --config commitlint.config.cjs -e -V" }, } ```

配置結束,現在當我們填寫commit信息的時候,前面就需要帶着下面的subject

'feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'chore', 'revert', 'build',

配置husky

npx husky add .husky/commit-msg

在生成的commit-msg文件中添加下面的命令

```

!/usr/bin/env sh

. "$(dirname -- "$0")/_/husky.sh"

pnpm commitlint ```

當我們 commit 提交信息時,就不能再隨意寫了,必須是 git commit -m 'fix: xxx' 符合類型的才可以,需要注意的是類型的後面需要用英文的 :,並且冒號後面是需要空一格的,這個是不能省略的。不然就會像下面這樣報錯了:

提交成功

強制使用pnpm下載包

根目錄創建scritps/preinstall.js文件,添加下面的內容

if (!/pnpm/.test(process.env.npm_execpath || '')) { console.warn( `\u001b[33mThis repository must using pnpm as the package manager ` + ` for scripts to work properly.\u001b[39m\n`, ) process.exit(1) }

配置命令

"scripts": { "preinstall": "node ./scripts/preinstall.js" }

當我們使用npm或者yarn來安裝包的時候,就會報錯了。原理就是在install的時候會觸發preinstall(npm提供的生命週期鈎子)這個命令。

最終我們的項目被集成了這個樣子

image.png

上述規範適集成思路用於各種項目,比如UI組件庫,工具庫,後台管理系統等等,只不過針對不同的技術有不同的lint包來配置,只要看懂了我的教程,你就可以自己配置了。

代碼地址

http://gitee.com/guigu-fe/guigu-sph-mall-admin/tree/template%2Fvue3-app-template/

歡迎star,歡迎PR。