題解 P3118 【[USACO15JAN]Moovie Mooving G】
程式碼規範
ESLint 的必要性
2017年年4⽉月13⽇日,騰訊⾼高階⼯工程師⼩小明在做充值業務時,修改了了蘋果 iap ⽀支付配 置,將 JSON 配置增加了了重複的 key 。程式碼釋出後,有⼩小部分使⽤用了了 vivo ⼿手 機的⽤使用者反饋充值⻚頁⾯面⽩白屏,⽆無法在 Now app 內進⾏行行充值。最後問題定位是: vivo ⼿手機使⽤用了了系統⾃自帶的 webview ⽽而沒有使⽤用 X5 核心,解析 JSON 時遇到 重複 key 報錯,導致⻚頁⾯面⽩白屏。
行業裡面優秀的 ESLInt 規範實踐
Airbnb: eslint-config-airbnb | eslint-config-airbnb-base
https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb | https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb-base
npm install eslint eslint-plugin-import eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y -D
npm install eslint-loader -D
npm install babel-eslint -D
npm install eslint-config-airbnb -D
然後在webpack.prod.js裡面,對module 裡面的 rule 數組裡,針對 js 檔案加入'eslint-loader'
建立 .eslintrc 檔案
module.exports = { "parser": "babel-eslint", "extends": "airbnb", "env": { "browser": true, "node": true } "rules": { "semi": "error" }, }
airbnb感覺是用的最多的,大而全,但是比較複雜
但是感覺谷歌的還稍微鬆一點
·alloyteam團隊 eslint-config-alloy(https://github.com/AlloyTeam/eslint-config-alloy)
·ivweb 團隊:eslint-config-ivweb(https://github.com/feflow/eslint-config-ivweb)
制定團隊的 ESLint 規範
不不重複造輪⼦子,基於 eslint:recommend 配置並 改進
能夠幫助發現程式碼錯誤的規則,全部開啟
幫助保持團隊的程式碼⻛風格統⼀一,⽽而不不是限制開發 體驗
規則名稱 | 錯誤級別 | 說明 |
---|---|---|
for-direction | error | for的迴圈方向必須正確 |
getter-return | error | getter必須有返回值,並且禁止返回值為 undefined,比如 return; |
no-wait-in-loop | off | 允許在迴圈裡面使用await |
no-console | off | 允許在程式碼裡面使用 console |
no-prototype-builtins | warn | 直接呼叫原型上的方法 |
valid-jsdoc | off | 函式註釋一定要遵循 jsdoc規則 |
no-template-curly-in-string | warn | 字串裡面出現{和}警告 |
accessor-paris | warn | getter和 setter沒有成對出現時給出警告 |
array-callback-return | error | 對於資料相關操作函式比如 reduce、map、filter等,callback 必須有return |
block-scoped-var | error | 把關鍵字 var 看成塊級作用域,防止變數提升的 bug |
class-mothods-use-this | error | 要求在 class裡面合理使用 this,如果某個方法沒有使用 this,則應該宣告為靜態方法 |
complexity | off | 關閉程式碼複雜度限制 |
default-case | error | switch-case 裡面要有 default分支 |
ESlint 如何執行落地
-
和 CI / CD系統整合
-
和 webpack 整合
方案一: webpack 與 CI / CD整合
在 build 前面加了一個 lint pipline
本地開發階段增加 precommit 鉤⼦子
安裝 husky
npm install husky --save-dev
增加 npm script,通過 lint-staged 增量量檢查修改的⽂檔案
"scripts": {
"precommit": "lint-staged"
},
"lint-staged": {
"linters": {
"*.{js,scss}": ["eslint --fix", "git add"]
}
},
方案二:webpack 與 ESLint 整合
使⽤用 eslint-loader,構建時檢查 JS 規範
module.exports = {
module: {
rules: [
{
test:/\.js$/,
exclude: /node_modules/,
use: [
"babel-loader",
"eslint-loader"
]
}
]
}
};