前言
代碼規範,也算是個老生常談的問題。如何寫出優秀漂亮的代碼,是每個程序員的必修課。得益於開源偉大思想,許多大廠都制定了一系列的代碼規範併發布在市場上。正所謂"前人栽樹,後人乘涼",我們就不必去大費周章的去定義代碼規範,只要做到遵守就好了。可能我們瞭解了有哪些代碼規範,但是在編碼當中我們難以百分百的遵守,所以我們還需要一個東西去約束我們編寫優秀漂亮的代碼。這裏就腳手架工程,從 IDE(編輯器)、代碼檢測、代碼美化、代碼提交共四個方面具體講解下如何保證代碼規範。
IDE(編輯器)
目前市場上流行各式各樣的編輯器,開發的同學也都自己鍾愛的編輯器,因此同一開發小組可能每個人都用不同的編輯器工作。爲了解決跨編輯器和 IDE 而造成的代碼規範問題,我使用EditorConfig。
1. 定義
什麼是 EditorConfig 呢?EditorConfig 有助於爲跨各種編輯器和 ide 處理同一項目的多個開發人員維護一致的編碼風格。EditorConfig 項目包括用於定義編碼樣式的文件格式和一組文本編輯器插件,這些插件使編輯器能夠讀取文件格式並遵循已定義的樣式。EditorConfig 文件很容易讀,而且它們與版本控制系統配合得很好。
2. 規則詳解
-
通配符模式
* 匹配除/之外的任意字符 ** 匹配任意字符串 ? 匹配任意單個字符 [name] 匹配name字符 [!name] 不匹配name字符 [s1,s2,s3] 匹配給定的字符串 [num1..num2] 匹配num1到mun2直接的整數
-
支持的屬性
indent_style 縮進風格,可選tab,space indent_size 縮進爲 space 時,縮進的字符數 tab_width 縮進爲 tab 時,縮進的寬度 end_of_line 換行符的類型,可選lf,cr,crlf charset 字符集,可選latin1,utf-8,utf-8-bom,utf-16be,utf-16le trim_trailing_whitespace 是否將行尾空格自動刪除 insert_final_newline 是否在文件結尾插入新行 root 表明是最頂層的配置文件,發現設爲true時,纔會停止查找.editorconfig文件
3. 使用
-
在工程根目錄下新建
.editorconfig
文件 -
在
.editorconfig
文件中編寫規則,參考如下:# https://editorconfig.org/ # EditorConfig文件使用INI格式。斜槓(/)作爲路徑分隔符,#或者;作爲註釋。路徑支持通配符: # 表明是最頂層的配置文件,發現設爲true時,纔會停止查找.editorconfig文件 root = true # * 匹配除/之外的任意字符 # ** 匹配任意字符串 # ? 匹配任意單個字符 # [name] 匹配name字符 # [!name] 不匹配name字符 # [s1,s2,s3] 匹配給定的字符串 # [num1..num2] 匹配num1到mun2直接的整數 [*] # 文件的charset。有以下幾種類型:latin1, utf-8, utf-8-bom, utf-16be, utf-16le charset = utf-8 # 縮進使用 tab 或者 space indent_style = space # 縮進爲 space 時,縮進的字符數 indent_size = 2 # 縮進爲 tab 時,縮進的寬度 tab_width = 2 # 換行符的類型。lf, cr, crlf三種 end_of_line = lf # 在文件結尾插入新行 insert_final_newline = true # 是否將行尾空格自動刪除 trim_trailing_whitespace = true [*.md] trim_trailing_whitespace = false [*.json] indent_size = 2
-
VSCODE 編輯器,需要安裝 EditorConfig for VS Code插件。關於插件安裝,詳情請參考文檔
TSLint
由於採用typescript
來編碼,這裏就使用TSLint
來檢查代碼。
1. 安裝
安裝分成兩種,局部安裝與全局安裝,強烈建議全局安裝
-
局部安裝(在項目的工作目錄中)
npm install tslint typescript --save-dev # or yarn add tslint typescript --dev
-
全局安裝
npm install tslint typescript -g # or yarn global add tslint typescript
2. 依賴庫
npm install tslint typescript
# or
yarn add tslint typescript
3. CLI 語法
-
詳解
-v, --version 版本 -c,--config 配置文件 -e,--exclude 排除那些文件 --fix 自動修復錯誤 --force 強制返回 code 0 -i,--init 生成 tslint.json 文件 -o,--out 文件名 輸出文件 --outputAbsolutePaths 是否爲絕對路徑 -r,--rules-dir 附件規則 -p,--project tsconfig.json 文件的位置
-
示例
tslint -p tsconfig.json -c tslint.json
-
退出 Code
0: 檢測成功,可能有警告 1: 使用了無效的命令行參數 2: 檢測失敗,有嚴重錯誤的規則出現
4. 配置
- 執行
yarn add tslint-config-prettier tslint-plugin-prettier tslint-eslint-rules tslint-react tslint-lines-between-class-members --dev
,添加插件 - 執行
tslint --init
,生成tslint.json
文件 - 在
tslint.json
文件中編寫檢查規則,參考如下:
關於具體規則描述,請參考文檔/* https://palantir.github.io/tslint/usage/configuration/ */ { "defaultSeverity": "error", "extends": ["tslint:recommended", "tslint-react", "tslint-eslint-rules", "tslint-config-prettier"], "linterOptions": { "exclude": ["__tests__", "node_modules"] }, "jsRules": { "max-line-length": { "options": [120] } }, /* https://palantir.github.io/tslint/rules/ */ "rules": { "prettier": [true, ".prettierrc.js"] /* 開啓prettier格式化,並使用.prettierrc.js規則 */, "max-line-length": { "options": [120] }, "no-console": { "severity": "error", "options": ["debug", "info", "log", "time", "timeEnd", "trace"] }, "object-literal-sort-keys": false, "interface-name": false, "jsx-no-lambda": false, "lines-between-class-members": true, "no-unused-expression": false, "member-access": [true, "no-public"] }, "rulesDirectory": ["node_modules/tslint-lines-between-class-members", "tslint-plugin-prettier"] }
- 執行檢測
tslint -p tsconfig.json -c tslint.json
- VSCODE 編輯器建議安裝
TSLint
插件,這樣在編碼中就能實時檢測代碼
5. 註釋標記
-
詳解
/* tslint:disable */ - 對文件的其餘部分禁用所有規則 /* tslint:enable */ - 對文件的其餘部分開啓所有規則 /* tslint:disable:rule1 rule2 rule3... */ - 對文件的其餘部分禁用列出的規則 /* tslint:disable:rule1 rule2 rule3... */ - 對文件的其餘部分啓用列出的規則 // tslint:disable-next-line - 禁用下一行的所有規則 // tslint:disable-line - 禁用當前行的所有規則 // tslint:disable-next-line:rule1 rule2 rule3... - 禁用下一行列出的規則
-
示例
function validRange (range: any) { return range.min <= range.middle && range.middle <= range.max; } /* tslint:disable:object-literal-sort-keys */ const range = { min: 5, middle: 10, // TSLint will *not* warn about unsorted keys here max: 20 }; /* tslint:enable:object-literal-sort-keys */ const point = { x: 3, z: 5, // TSLint will warn about unsorted keys here y: 4, } console.log(validRange(range));
6. 第三方工具
- grunt-tslint(Grunt)
- gulp-tslint(Gulp)
- eclipse-tslint(Eclipse)
- linter-tslint(Atom)
- vscode-tslint(Visual Studio Code)
- syntastic(VIM)
- Web Analyzer(Visual Studio)
- Webstorm
- mocha-tslint(Mocha)
- tslint.tmbundle(TextMate)
- generator
- Flycheck(Emacs)
Prettier
美化代碼,Prettier
是必不可少的
1. 安裝
安裝分成兩種,本地安裝與全局安裝,強烈建議全局安裝
-
局部安裝(在項目的工作目錄中)
npm install --save-dev --save-exact prettier # or yarn add prettier --dev --exact
-
全局安裝
npm install --global prettier # or yarn global add prettier
2. ClI 語法
- –check: 檢查文件是否已格式化
- –debug-check: 檢測 prettier 代碼是否影響代碼的正確性
- –find-config-path and --config: 查找配置文件
- –ignore-path: 忽略文件的路徑
- –require-pragma: 文件頭顯示特殊註釋,方便格式化
- –insert-pragma: 文件的頭部插入@format 標識,配合–require-pragma 使用
- –list-different: 列出格式化差異
- –no-config: 不查找配置文件,使用默認設置
- –no-editorconfig: 解析配置時不要考慮.editorconfig
- –with-node-modules: 格式化 node-modules 中的代碼
- –write: 重寫已處理的所有文件
- –loglevel: 更改 CLI 的日誌記錄級別,可選 error、warn、log、 debug、silent
- –stdin-filepath
3. 選項
- Print Width: 換行字符串長度
- Tab Width: 每個縮進的空格數
- Tabs: 縮進風格,是否用 tab 代替 space
- Semicolons: 句末加分號
- Quotes: 單引號代替雙引號
- JSX Quotes: 在 JSX 裏用單引號代替雙引號
- Trailing Commas: 在多行情況下,儘可能打印後面的逗號
- Bracket Spacing: 在對象文字的方括號之間打印空格
- JSX Brackets: 將多行 JSX 元素的 > 放在最後一行的末尾,而不是單獨放在下一行
- Arrow Function Parentheses: 在一個單獨的箭頭函數參數周圍加上圓括號
- Range: 格式化文件的某一段
- Parser: 指定解析器
- File Path: 指定要使用的文件名來推斷使用哪個解析器
- Require pragma: 是否只對特殊註釋的文件格式化
- Insert Pragma: 是否插入特殊註釋符,配合 Require pragma 使用
- Prose Wrap: 是否換行
- HTML Whitespace Sensitivity: 爲 HTML 文件指定全局空白
- End of Line: 文本行尾
4. 美化配置
- 執行
touch .prettierrc.js
,生成.prettierrc.js
文件 - 在
.prettierrc.js
文件中編寫檢查規則,參考如下:module.exports = { // parser: 'typescript', // 解析器,會自動推斷 printWidth: 120, // 換行字符串閾值 semi: true, // 句末加分號 singleQuote: true, // 用單引號 useTabs: false, // 是否用Tab縮進 tabWidth: 2, // 每一個水平縮進的空格數 trailingComma: 'none', // 最後一個對象元素加逗號,可選 none|es5|all bracketSpacing: true, // 對象,數組加空格 jsxBracketSameLine: false, // jsx > 是否另起一行 arrowParens: 'avoid', // (x) => {} 是否要有小括號,可選 avoid|always requirePragma: false, // 是否要註釋來決定是否格式化代碼 proseWrap: 'preserve', // 是否要換行,可選 always|never|preserve endOfLine: 'auto', // 行尾風格,可選 auto|lf|crlf|cr htmlWhitespaceSensitivity: 'css' //HTML文件指定全局空白, 可選css|strict|ignore };
- 執行
prettier --write App.tsx src/*.{ts,tsx,d.ts}
- VSCODE 編輯器建議安裝
Prettier
插件,並且在 VSCODE 設置裏開啓"editor.formatOnSave": true,
,這樣保存的時候話就會格式化代碼,並且會智能的修復錯誤的編碼格式
5.忽略配置
-
文件忽略, 執行
touch .prettierignore
,生成.prettierignore
文件添加需要忽略的文件,參考# 忽略 tsconfig.json tsconfig.json
-
註釋忽略,
/_ prettier-ignore _/
or// prettier-ignore
or/* prettier-ignore */
-
註釋忽略某部分代碼,
<!-- prettier-ignore-start --> <!-- prettier-ignore-end -->
Pre-commit Hook
Pre-commit Hook 是配合Git
使用的,它能夠在提交代碼之前幫助你格式化代碼,如果有不符合規範的代碼,會強制阻止提交,直到你修復了不符合規範的代碼才能提交成功。
1.安裝
yarn add lint-staged husky --dev
2.配置
分成兩種配置方式,任先其一
-
方式一,在
package.json
插入以下代碼"husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { "linters": { "*.{ts,tsx}": [ "node node_modules/tslint/bin/tslint -p ./tsconfig.json -c tslint.json --fix", "node node_modules/prettier/bin-prettier.js --write", "git add" ], "*.{js,json}": [ "node node_modules/prettier/bin-prettier.js --write", "git add" ], "*.{md,html}": [ "node node_modules/prettier/bin-prettier.js --write", "git add" ] }, "ignore": [ "package.json" ] }
-
方式二,分別創建
.huskyrc.js
和lint-staged.config.js
文件,插入以下代碼.huskyrc.js module.exports = { skipCI: false, hooks: { 'pre-commit': 'node node_modules/lint-staged/index.js' // 執行 node_modules 中的lint-staged 腳本 } };
lint-staged.config.js module.exports = { linters: { '*.{ts,tsx,d.ts}': [ 'node node_modules/tslint/bin/tslint -p ./tsconfig.json -c tslint.json --fix', 'node node_modules/prettier/bin-prettier.js --write', 'git add' ], '*.{js,json}': ['node node_modules/prettier/bin-prettier.js --write', 'git add'], '*.{md,html}': ['node node_modules/prettier/bin-prettier.js --write', 'git add'] }, ignore: ['package.json'], relative: true };
3.使用
我這裏只配置pre-commit
了命令, 執行git commit -m 'comment'
提交代碼就能使用 Hook
當使用 git commit
時, husky
會執行lint-staged
腳本並且讀取lint-staged.config.js
中的配置信息
hooks
還支持很多種命令,commit-msg
、pre-push
、post-merge
等,都存放在./git/hooks
文件夾下
VSCode 設置,僅供參考
{
"editor.tabSize": 2, // 一個製表符等於的空格數
"editor.minimap.enabled": false, // 隱藏右側小地圖
"explorer.autoReveal": false, // 控制資源管理器是否應在打開文件時自動顯示它們
"javascript.updateImportsOnFileMove.enabled": "always",
"editor.formatOnSave": true, // 保存時格式化代碼
"workbench.colorTheme": "Visual Studio Light", // 主題
"breadcrumbs.enabled": true, // 顯示文件路徑位置
"editor.renderWhitespace": "all", // 文件保存時去除末尾空格
"files.trimTrailingWhitespace": true, // 啓用後,將在保存文件時剪裁尾隨空格
"prettier.eslintIntegration": true, // 開啓prettier配合eslint使用
"prettier.tslintIntegration": true, // 開啓prettier配合tsslint使用
"tslint.alwaysShowRuleFailuresAsWarnings": false // tslint顯示檢測失敗爲waring
}
總結
現在是不是覺得代碼規範很簡單呢?只要我們合理的使用這些插件,一樣能編寫出優秀漂亮的代碼。可能開始時插件拋出的錯誤莫名其妙,關鍵在於我們要了解這些插件的作用,特別要理解TSLint
中的規則,搞清楚了這些你才知道怎樣編寫出優美的代碼。不管怎樣,代碼規範無論是對個人開發還是對團隊開發都是非常重要的,值得我們使用。相信,每個優秀的開發者代碼規範是必不可少的!
效果圖
寫在最後
-
當
TLsint
檢測不過時,會強制阻止Prettier
格式化代碼 -
對 VSCODE 編輯器,
TSLint
和ESLint
插件建議不要同時使用,可能會存在衝突 -
對 VSCODE 編輯器,編輯
TSLint
的規則可能不會立即生效,應該是有緩存,建議重啓 VSCODE -
關於如何使用 ESLint 檢測代碼規範,可以參考這篇文章:ReactNative 如何配置 ESLint,Prettier,Pre-commit Hook