Eslint Style Demo
配置React+Eslint+Airbnb
新建項目
按照上一篇文章的方法新建一個新項目eslint-style-demo
安裝eslint
- 安裝
eslint
,可選本地安裝或者全局安裝,這里選擇本地安裝
npm i -D eslint
- 初始化并生成配置文件
.eslintrc.js
,各初始化參數可以先隨便選,后面再做修改
./node_modules/.bin/eslint --init
- 安裝對babel和react的支持
npm i -D babel-eslint eslint-plugin-react
- 修改
.eslintrc.js
配置文件如下,打開一個js文件可以查看eslint效果
module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly",
"Babel": true,
"React": true
},
"parser": "babel-eslint",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
}
};
引入Airbnb規則
- 安裝相關插件
npm i -D eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y
- 修改
.eslintrc.js
配置文件,設置extends部分為airbnb規則,增加rules
module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": [
"airbnb",
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly",
"Babel": true,
"React": true
},
"parser": "babel-eslint",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
//關閉換行符操作系統格式問題
"linebreak-style": [
"off",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
// 禁止縮進錯誤
"indent": 0,
// 關閉不允許使用 no-tabs
"no-tabs": "off",
"no-console": 1,
// 設置不沖突 underscore 庫
"no-underscore-dangle":0,
// 箭頭函數直接返回的時候不需要 大括號 {}
"arrow-body-style": [2, "as-needed"],
"no-alert":"error",
// 設置是否可以重新改變參數的值
"no-param-reassign": 0,
// 允許使用 for in
"no-restricted-syntax": 0,
"guard-for-in": 0,
// 不需要每次都有返回
"consistent-return":0,
// 允許使用 arguments
"prefer-rest-params":0,
// 允許返回 await
"no-return-await":0,
// 不必在使用前定義 函數
"no-use-before-define": 0,
// 允許代碼后面空白
"no-trailing-spaces": 0,
// 關閉大括號內的換行符要求
"object-curly-newline": 0,
// 有一些 event 的時候,不需要 role 屬性,不需要其他解釋
"jsx-a11y/no-static-element-interactions":0,
"jsx-a11y/click-events-have-key-events":0,
// 類成員之間空行問題
"lines-between-class-members":0,
// 不區分是否在 despendencies
"import/no-extraneous-dependencies": 0,
// 引用時候根據根目錄基礎
"import/no-unresolved": 0,
// 關閉解構賦值報錯
"react/destructuring-assignment": 0,
// 允許在 .js 和 .jsx 文件中使用 jsx
"react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
// jsx > 緊跟著屬性
"react/jsx-closing-bracket-location": [1, "after-props"],
// 不區分是否是 無狀態組件
"react/prefer-stateless-function": 0,
// prop-types忽略children屬性
"react/prop-types": [1, { ignore: ["children"]}],
// 關閉禁止prop-types類型
"react/forbid-prop-types": 0,
// 關閉default-props檢查
"react/require-default-props":0
}
};
- 在App.js組件測試查看效果