ESLint
ESLint 是一個按照規則給出報告的代碼檢測工具,使用它可以避免低級錯誤和統一代碼風格,這對公司團隊開發非常實用。
安裝
1.全局安裝
如果你想使用ESLint適用於你所有的項目,建議全局安裝ESLint
npm i -g eslint
初始化配置文件
./node_modules/.bin/eslint --init
2.局部安裝
單個項目使用
npm i -D eslint
初始化配置文件
eslint --inint
3.安裝步驟
至此,安裝完成。
配置
指定執行環境
"env": {
browser: true,
node: true,
},
指定全局變量
- 使用註釋來配置
/* global __DEV__, fetch */
/* global __DEV__:true, fetch:true */
- 使用配置文件來配置
"globals": {
"__DEV__": true,
"fetch": true
},
規則
規則等級有三種:
- “off”或者0: 關閉規則
- “warn”或者1: 打開規則,作爲警告。
- “error”或者2: 打開規則,作爲錯誤。
例如:
- 使用註釋來配置
/* eslint no-console: "off", no-undef: "error" */
/* eslint no-console: 0, no-undef: 2 */
- 使用配置文件來配置
"rules": {
"no-console": "off",
"no-undef": "off",
"no-useless-constructor": "off",
"import/no-extraneous-dependencies": [
"error",
{
"devDependencies": true,
"optionalDependencies": false,
"peerDependencies": false
}
],
"react/jsx-filename-extension": "off"
}
當然,也可以在註釋中關閉規則
/* eslint-disable */
/* eslint-enable */
/* eslint-disable no-alert, no-console */
/* eslint-enable no-alert, no-console */
使用方法
在package.json
文件中加入以下代碼
"scripts": {
"lint": "eslint --ext .js ./src --fix",
}
命令行工具下執行yarn run lint
, 即會檢測代碼。
Prettier
Prettier是代碼格式化工具,能夠統一個人或者團隊的代碼風格。
安裝
npm i -D prettier
配置
在工程根目錄下創建.prettierrc.js
文件,
module.exports = {
printWidth: 120, // 換行字符串閾值
semi: true, // 句末加分號
singleQuote: true, // 用單引號
trailingComma: 'none', // 最後一個對象元素加逗號
bracketSpacing: true, // 對象,數組加空格
jsxBracketSameLine: false, // jsx > 是否另起一行
arrowParens: 'avoid', // (x) => {} 是否要有小括號
requirePragma: false, // 是否要註釋來決定是否格式化代碼
proseWrap: 'preserve' // 是否要換行
};
插件
npm i -D eslint eslint-config-prettier eslint-plugin-prettier
結合.eslintrc.json
配置
"extends": ["airbnb", "prettier", "plugin:prettier/recommended"],
"plugins": ["react", "prettier"],
使用方法
在package.json文件中加入以下代碼
"scripts": {
"prettier": "prettier --write src/**/*.js"
}
在命令行工具下執行 prettier --write src/**/*.js
, src
對應的是你文件夾
Pre-commit Hook
Pre-commit Hook是在Git
提交之前用來檢查待提交代碼是否有錯誤的工具。
安裝
npm i -D husky lint-staged pretty-quick
配置
在package.json文件中加入以下代碼
"scripts": {
"precommit": "pretty-quick --staged",
},
"lint-staged": {
"*.{js,json,md}": [
"prettier --write",
"git add"
],
"*.js": [
"yarn lint --fix",
"git add"
]
},
使用
使用Git
提交代碼的時候,會自動檢測代碼並進行格式化,如何有錯誤會終止push
VSCode
- 安裝ESLint Prettier插件
- 在設置中添加
"editor.formatOnSave": true,
"javascript.format.enable": false,
"prettier.eslintIntegration": true
當你保存時會自動修復一些空格縮進、單雙引號及句末是否加;
的錯誤,但是你變量未聲明等錯誤需要手動去修復。
效果圖
寫在最後
剛開始使用ESLint的時候,你可能會遇到各種各樣的紅色波浪線錯誤。不要覺得莫名其妙,這說明你的代碼規範有很多值得去補充修正的地方,好好去弄明白eslint
中的規則,形成良好的代碼風格,這不管是對個人還是團隊而言都是值得使用的。
附上Demo,感興趣的可以看一看。