天天看點

react 使用 eslint 的三種代碼檢查方案總結,多了解點--讓代碼更完美....

1、介紹

    ESLint 是一個可擴充,每條規則獨立,被設計為完全可配置的lint工具。

    可以用來檢測代碼,避免低級錯誤

    可以用來規範代碼的開發風格,統一代碼習慣。

2、為什麼使用 ESLint ?

    統一代碼規範 :

    在開發中,可能會遇到很多不同的同僚同時開發一個項目 ,或者在工作的調整中,會有接手一個項目,

    這時候,就會發現完全和自己的開發風格不同,該起來非常痛苦。ESLint 統一代碼規範,是我們在不

    同的項目更好的融入項目開發。

    檢測代碼 :

    在開發中,會遇到一些非常低級的錯誤,如 alert 發到生産, 少一個 { 等,用了 ESLint ,我們可以在送出

    代碼前,進行代碼檢測,避免這些不必要的錯誤發到生産。

3、ESLint 項目中規範的方案

    ESLint + Airbnb

    ESLint + Standard 

    ESLint + Prettier 

    大概就三種方案,可以根據不同的需求/業務進行搭建。

 執行檢查,并且格式化代碼

eslint --fix
      

  

4、ESLint + Airbnb 項目配置

  全局安裝依賴包:

npm install -g eslint       
npm install -g eslint-config-airbnb eslint-plugin-import eslint-plugin-react eslint-plugin-jsx-a11y babel-eslint      

   包介紹:

     eslint : 不必要介紹了。可以直接到官網上檢視

       eslint-config-airbnb :  配置一些 eslint rules 的規範

     eslint-plugin-import :在使用 import 的時候,一些 rules 規範

       eslint-plugin-react : 一些 react 的 eslint 的 rules 規範

       eslint-plugin-jsx-a11y: 一些 jsx 的 rules 規範

  配置 eslintrc 檔案:

{
    // 環境,這裡可以設定環來做差別判斷
    "env": {
        "browser": true,
        "commonjs": true,
        "es6": true
    },
    // 使用的擴充庫
    "extends": ["airbnb"],
    // 解析器用于解析代碼
    "parser": "babel-eslint",
    // 解析器配置
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 2018,
        "sourceType": "module"
    },
    // 可以全局使用變量
    "globals": {
        "Babel": true,
        
        "React": true
    },
    // 第三方插件
    "plugins": [
        "react"
    ],
    // 規則配置
    "rules": {
        "linebreak-style": [
            "error",
            "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,


        // 有一些 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,

        // 允許在 .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

    }
}
      

  大功告成!

5、ESLint + Standard 項目配置

  全局安裝依賴包 :

npm install -g eslint babel-eslint
npm install  eslint-config-standard eslint-config-standard-react eslint-plugin-standard eslint-plugin-promise eslint-plugin-import  eslint-plugin-react
      

  包介紹:

    config-standard : standard 的規則配置包擴充

    config-standard-react :   react的擴充

    plugin-standard : standard規則

    plugin-import : 同上

    plugin-react : 同上

    

   配置 eslintrc 檔案:

{
    // 環境,這裡可以設定環來做差別判斷
    "env": {
        "browser": true,
        "commonjs": true,
        "es6": true
    },
    // 使用的擴充庫
    "extends": ["standard","standard-react"],
    // 解析器用于解析代碼
    "parser": "babel-eslint",
    // 解析器配置
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 2018,
        "sourceType": "module"
    },
    // 可以全局使用變量
    "globals": {
        "Babel": true,
        
        "React": true
    },
    // 第三方插件
    "plugins": [],
    // 規則配置
    "rules": {
       // ... 自行定義
    }
}
      

  兩個擴充配置介紹:

    standard :js style rules 。是 js 格式樣式的以及規則定義的集合

    standard-react : react 以及 jsx 規則定義集合,他依賴  plugin-react, standard-jsx 

     

  規則配置的話,可以檢視 plugin-react , standard , standard-jsx 規則清單。

6、 ESLint + Prettier 項目配置

npm install -g eslint 
nam -g install eslint-plugin-prettier eslint-config-prettier babel-eslint prettier eslint-plugin-html --save-dev
      
{
    // 環境,這裡可以設定環來做差別判斷
    "env": {
        "browser": true,
        "commonjs": true,
        "es6": true
    },
    // 使用的擴充庫
    "extends": ["eslint:recommended","prettier"],
    // 解析器用于解析代碼
    "parser": "babel-eslint",
    // 解析器配置
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 2018,
        "sourceType": "module"
    },
    // 可以全局使用變量
    "globals": {
        "Babel": true,
        
        "React": true
    },
    // 第三方插件
    "plugins": [
        "prettier",
        "html", // 用于vue
    ],
    // 規則配置
    "rules": {
       // ... 自行定義
    }
}
   
      

  和上面兩種方案差不多,把擴充改為對應的庫。

  三種方案:

    第一個種我覺得很好用,尤其很适合開發 react 項目

    第二種用到很少,不過也不錯。

    第三種比較适合 vue 項目,個人這麼認為。

7、webstorm  配置 eslint

  1、自帶的 eslint 配置

      打開 setting 

react 使用 eslint 的三種代碼檢查方案總結,多了解點--讓代碼更完美....

    2.使用插件ESLint

    下載下傳 plugin 插件

react 使用 eslint 的三種代碼檢查方案總結,多了解點--讓代碼更完美....

    然後在 setting 中好到 eslint ,同一一樣配置即可。

8、項目優化

  在代碼送出前進行 代碼規範設定及其檢測

  那麼所有代碼都是統一的了。 

 

  1、安裝 git hook 包

npm install --dev-save husky
npm install --dev-save lint-staged
      

  修改 package.json 進行代碼優化

// 在 scripts 添加 precommit
"scripts": {
    "dev": "webpack-dev-server --config ./webpack/webpack.config.dev.js",
    "build": "webpack --config ./webpack/webpack.config.prod.js",
    // 在執行 git commit  執行某一個執行
    "precommit": "NODE_ENV=node lint-staged"
},
// 對代碼進行修正,并且對代碼進行檢測
"lint-staged": {
    "*.{js,jsx}": [
        "eslint --fix",  // 修正,檢測
         "git add"   // 重新送出代碼
        ]
},
      

*、常見的檢查介紹 ( 複制來的 )

"no-alert": 0,//禁止使用alert confirm prompt
"no-array-constructor": 2,//禁止使用數組構造器
"no-bitwise": 0,//禁止使用按位運算符
"no-caller": 1,//禁止使用arguments.caller或arguments.callee
"no-catch-shadow": 2,//禁止catch子句參數與外部作用域變量同名
"no-class-assign": 2,//禁止給類指派
"no-cond-assign": 2,//禁止在條件表達式中使用指派語句
"no-console": 2,//禁止使用console
"no-const-assign": 2,//禁止修改const聲明的變量
"no-constant-condition": 2,//禁止在條件中使用常量表達式 if(true) if(1)
"no-continue": 0,//禁止使用continue
"no-control-regex": 2,//禁止在正規表達式中使用控制字元
"no-debugger": 2,//禁止使用debugger
"no-delete-var": 2,//不能對var聲明的變量使用delete操作符
"no-div-regex": 1,//不能使用看起來像除法的正規表達式/=foo/
"no-dupe-keys": 2,//在建立對象字面量時不允許鍵重複 {a:1,a:1}
"no-dupe-args": 2,//函數參數不能重複
"no-duplicate-case": 2,//switch中的case标簽不能重複
"no-else-return": 2,//如果if語句裡面有return,後面不能跟else語句
"no-empty": 2,//塊語句中的内容不能為空
"no-empty-character-class": 2,//正規表達式中的[]内容不能為空
"no-empty-label": 2,//禁止使用空label
"no-eq-null": 2,//禁止對null使用==或!=運算符
"no-eval": 1,//禁止使用eval
"no-ex-assign": 2,//禁止給catch語句中的異常參數指派
"no-extend-native": 2,//禁止擴充native對象
"no-extra-bind": 2,//禁止不必要的函數綁定
"no-extra-boolean-cast": 2,//禁止不必要的bool轉換
"no-extra-parens": 2,//禁止非必要的括号
"no-extra-semi": 2,//禁止多餘的冒号
"no-fallthrough": 1,//禁止switch穿透
"no-floating-decimal": 2,//禁止省略浮點數中的0 .5 3.
"no-func-assign": 2,//禁止重複的函數聲明
"no-implicit-coercion": 1,//禁止隐式轉換
"no-implied-eval": 2,//禁止使用隐式eval
"no-inline-comments": 0,//禁止行内備注
"no-inner-declarations": [2, "functions"],//禁止在塊語句中使用聲明(變量或函數)
"no-invalid-regexp": 2,//禁止無效的正規表達式
"no-invalid-this": 2,//禁止無效的this,隻能用在構造器,類,對象字面量
"no-irregular-whitespace": 2,//不能有不規則的空格
"no-iterator": 2,//禁止使用__iterator__ 屬性
"no-label-var": 2,//label名不能與var聲明的變量名相同
"no-labels": 2,//禁止标簽聲明
"no-lone-blocks": 2,//禁止不必要的嵌套塊
"no-lonely-if": 2,//禁止else語句内隻有if語句
"no-loop-func": 1,//禁止在循環中使用函數(如果沒有引用外部變量不形成閉包就可以)
"no-mixed-requires": [0, false],//聲明時不能混用聲明類型
"no-mixed-spaces-and-tabs": [2, false],//禁止混用tab和空格
"linebreak-style": [0, "windows"],//換行風格
"no-multi-spaces": 1,//不能用多餘的空格
"no-multi-str": 2,//字元串不能用\換行
"no-multiple-empty-lines": [1, {"max": 2}],//空行最多不能超過2行
"no-native-reassign": 2,//不能重寫native對象
"no-negated-in-lhs": 2,//in 操作符的左邊不能有!
"no-nested-ternary": 0,//禁止使用嵌套的三目運算
"no-new": 1,//禁止在使用new構造一個執行個體後不指派
"no-new-func": 1,//禁止使用new Function
"no-new-object": 2,//禁止使用new Object()
"no-new-require": 2,//禁止使用new require
"no-new-wrappers": 2,//禁止使用new建立包裝執行個體,new String new Boolean new Number
"no-obj-calls": 2,//不能調用内置的全局對象,比如Math() JSON()
"no-octal": 2,//禁止使用八進制數字
"no-octal-escape": 2,//禁止使用八進制轉義序列
"no-param-reassign": 2,//禁止給參數重新指派
"no-path-concat": 0,//node中不能使用__dirname或__filename做路徑拼接
"no-plusplus": 0,//禁止使用++,--
"no-process-env": 0,//禁止使用process.env
"no-process-exit": 0,//禁止使用process.exit()
"no-proto": 2,//禁止使用__proto__屬性
"no-redeclare": 2,//禁止重複聲明變量
"no-regex-spaces": 2,//禁止在正規表達式字面量中使用多個空格 /foo bar/
"no-restricted-modules": 0,//如果禁用了指定子產品,使用就會報錯
"no-return-assign": 1,//return 語句中不能有指派表達式
"no-script-url": 0,//禁止使用javascript:void(0)
"no-self-compare": 2,//不能比較自身
"no-sequences": 0,//禁止使用逗号運算符
"no-shadow": 2,//外部作用域中的變量不能與它所包含的作用域中的變量或參數同名
"no-shadow-restricted-names": 2,//嚴格模式中規定的限制辨別符不能作為聲明時的變量名使用
"no-spaced-func": 2,//函數調用時 函數名與()之間不能有空格
"no-sparse-arrays": 2,//禁止稀疏數組, [1,,2]
"no-sync": 0,//nodejs 禁止同步方法
"no-ternary": 0,//禁止使用三目運算符
"no-trailing-spaces": 1,//一行結束後面不要有空格
"no-this-before-super": 0,//在調用super()之前不能使用this或super
"no-throw-literal": 2,//禁止抛出字面量錯誤 throw "error";
"no-undef": 1,//不能有未定義的變量
"no-undef-init": 2,//變量初始化時不能直接給它指派為undefined
"no-undefined": 2,//不能使用undefined
"no-unexpected-multiline": 2,//避免多行表達式
"no-underscore-dangle": 1,//辨別符不能以_開頭或結尾
"no-unneeded-ternary": 2,//禁止不必要的嵌套 var isYes = answer === 1 ? true : false;
"no-unreachable": 2,//不能有無法執行的代碼
"no-unused-expressions": 2,//禁止無用的表達式
"no-unused-vars": [2, {"vars": "all", "args": "after-used"}],//不能有聲明後未被使用的變量或參數
"no-use-before-define": 2,//未定義前不能使用
"no-useless-call": 2,//禁止不必要的call和apply
"no-void": 2,//禁用void操作符
"no-var": 0,//禁用var,用let和const代替
"no-warning-comments": [1, { "terms": ["todo", "fixme", "xxx"], "location": "start" }],//不能有警告備注
"no-with": 2,//禁用with

"array-bracket-spacing": [2, "never"],//是否允許非空數組裡面有多餘的空格
"arrow-parens": 0,//箭頭函數用小括号括起來
"arrow-spacing": 0,//=>的前/後括号
"accessor-pairs": 0,//在對象中使用getter/setter
"block-scoped-var": 0,//塊語句中使用var
"brace-style": [1, "1tbs"],//大括号風格
"callback-return": 1,//避免多次調用回調什麼的
"camelcase": 2,//強制駝峰法命名
"comma-dangle": [2, "never"],//對象字面量項尾不能有逗号
"comma-spacing": 0,//逗号前後的空格
"comma-style": [2, "last"],//逗号風格,換行時在行首還是行尾
"complexity": [0, 11],//循環複雜度
"computed-property-spacing": [0, "never"],//是否允許計算後的鍵名什麼的
"consistent-return": 0,//return 後面是否允許省略
"consistent-this": [2, "that"],//this别名
"constructor-super": 0,//非派生類不能調用super,派生類必須調用super
"curly": [2, "all"],//必須使用 if(){} 中的{}
"default-case": 2,//switch語句最後必須有default
"dot-location": 0,//對象通路符的位置,換行的時候在行首還是行尾
"dot-notation": [0, { "allowKeywords": true }],//避免不必要的方括号
"eol-last": 0,//檔案以單一的換行符結束
"eqeqeq": 2,//必須使用全等
"func-names": 0,//函數表達式必須有名字
"func-style": [0, "declaration"],//函數風格,規定隻能使用函數聲明/函數表達式
"generator-star-spacing": 0,//生成器函數*的前後空格
"guard-for-in": 0,//for in循環要用if語句過濾
"handle-callback-err": 0,//nodejs 處理錯誤
"id-length": 0,//變量名長度
"indent": [2, 4],//縮進風格
"init-declarations": 0,//聲明時必須賦初值
"key-spacing": [0, { "beforeColon": false, "afterColon": true }],//對象字面量中冒号的前後空格
"lines-around-comment": 0,//行前/行後備注
"max-depth": [0, 4],//嵌套塊深度
"max-len": [0, 80, 4],//字元串最大長度
"max-nested-callbacks": [0, 2],//回調嵌套深度
"max-params": [0, 3],//函數最多隻能有3個參數
"max-statements": [0, 10],//函數内最多有幾個聲明
"new-cap": 2,//函數名首行大寫必須使用new方式調用,首行小寫必須用不帶new方式調用
"new-parens": 2,//new時必須加小括号
"newline-after-var": 2,//變量聲明後是否需要空一行
"object-curly-spacing": [0, "never"],//大括号内是否允許不必要的空格
"object-shorthand": 0,//強制對象字面量縮寫文法
"one-var": 1,//連續聲明
"operator-assignment": [0, "always"],//指派運算符 += -=什麼的
"operator-linebreak": [2, "after"],//換行時運算符在行尾還是行首
"padded-blocks": 0,//塊語句内行首行尾是否要空行
"prefer-const": 0,//首選const
"prefer-spread": 0,//首選展開運算
"prefer-reflect": 0,//首選Reflect的方法
"quotes": [1, "single"],//引号類型 `` "" ''
"quote-props":[2, "always"],//對象字面量中的屬性名是否強制雙引号
"radix": 2,//parseInt必須指定第二個參數
"id-match": 0,//命名檢測
"require-yield": 0,//生成器函數必須有yield
"semi": [2, "always"],//語句強制分号結尾
"semi-spacing": [0, {"before": false, "after": true}],//分号前後空格
"sort-vars": 0,//變量聲明時排序
"space-after-keywords": [0, "always"],//關鍵字後面是否要空一格
"space-before-blocks": [0, "always"],//不以新行開始的塊{前面要不要有空格
"space-before-function-paren": [0, "always"],//函數定義時括号前面要不要有空格
"space-in-parens": [0, "never"],//小括号裡面要不要有空格
"space-infix-ops": 0,//中綴操作符周圍要不要有空格
"space-return-throw-case": 2,//return throw case後面要不要加空格
"space-unary-ops": [0, { "words": true, "nonwords": false }],//一進制運算符的前/後要不要加空格
"spaced-comment": 0,//注釋風格要不要有空格什麼的
"strict": 2,//使用嚴格模式
"use-isnan": 2,//禁止比較時使用NaN,隻能用isNaN()
"valid-jsdoc": 0,//jsdoc規則
"valid-typeof": 2,//必須使用合法的typeof的值
"vars-on-top": 2,//var必須放在作用域頂部
"wrap-iife": [2, "inside"],//立即執行函數表達式的小括号風格
"wrap-regex": 0,//正規表達式字面量用小括号包起來
"yoda": [2, "never"]//禁止尤達條件
      

   https://www.cnblogs.com/jiebba/p/9601626.html 

   我的部落格 :  XiaoLong's Blog

   部落格園小結巴巴: https://www.cnblogs.com/jiebba

感覺可以就推薦下吧!!

感覺可以就推薦下吧!!