js代碼規範之---Eslint安裝與配置

1、Eslint安裝

1.全局安裝

若是你想使 ESLint 適用於你全部的項目,建議全局安裝 ESLinthtml

$ npm install -g eslint

初始化配置文件vue

$ eslint --init

2.局部安裝

$ npm install eslint --save-dev

初始化配置文件node

$ ./node_modules/.bin/eslint --init

3.webpack中配置eslint

須要安裝eslint-loader解析.eslint文件react

{
        test: /\.(js|jsx|mjs)$/,
        enforce: 'pre',
        use: [
          {
            options: {
              formatter: eslintFormatter,
              eslintPath: require.resolve('eslint'),
              
            },
            loader: require.resolve('eslint-loader'),
          },
        ],
        include: paths.appSrc, //也能夠用exclude排除不須要檢查的目錄或者用.eslintignore
},

2、ESlint配置

1.配置文件類型與優先級順序

  1. .eslintrc.js - 使用 .eslintrc.js 而後輸出一個配置對象
  2. .eslintrc.yaml - 使用 .eslintrc.yaml 或 .eslintrc.yml 去定義配置的結構。
  3. .eslintrc.yml
  4. .eslintrc.json - 使用 .eslintrc.json 去定義配置的結構,ESLint 的 JSON 文件容許 JavaScript 風格的註釋
  5. .eslintrc(已棄用)
  6. package.json - 在 package.json 裏建立一個 eslintConfig屬性,在那裏定義你的配置

2.plugin屬性

ESLint 支持使用第三方插件(以eslint-plugin-開頭的npm包),在使用插件以前,必須使用 npm 安裝。如eslint-plugin-react、eslint-plugin-vue等webpack

module.exports = {
    "plugins": [
        "react"
    ],
    "extends": [
        "eslint:recommended"
    ],
    "rules": {
       "no-set-state": "off"
    }
}

3.extends屬性

一個配置文件能夠被基礎配置中的已啓用的規則繼承。可使用如下規則繼承:web

(1)"eslint:recommended"

繼承Eslint中推薦的(打鉤的)規則項正則表達式

module.exports = {
    "extends": "eslint:recommended",
    "rules": {
        
    }
}

(2)使用別人寫好的規則包(以eslint-config-開頭的npm包),如eslint-config-standard

module.exports = {
    "extends": "standard",
    "rules": {
        
    }
}

(3)使用Eslint插件中命名的配置

module.exports = {
    "plugins": [
        "react"
    ],
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended"
    ],
    "rules": {
       "no-set-state": "off"
    }
}

(4)使用"eslint:all",繼承Eslint中全部的核心規則項

module.exports = {
    "extends": "eslint:all",
    "rules": {
        // override default options
        "comma-dangle": ["error", "always"],
        "indent": ["error", 2],
        "no-cond-assign": ["error", "always"],

        // disable now, but enable in the future
        "one-var": "off", // ["error", "never"]

        // disable
        "init-declarations": "off",
        "no-console": "off",
        "no-inline-comments": "off",
    }
}

4.rules屬性(根據本身的須要進行配置)

(1)Eslint部分核心規則

"rules": {
        /**
        **這些規則與 JavaScript 代碼中可能的錯誤或邏輯錯誤有關
        **/
        "for-direction":"error",//強制 「for」 循環中更新子句的計數器朝着正確的方向移動
        "getter-return":"error",//強制在 getter 屬性中出現一個 return 語句
        "no-await-in-loop":"error",//禁止在循環中 出現 await
        "no-compare-neg-zer":"error",//禁止與 -0 進行比較
        "no-cond-assign":[//禁止在條件語句中出現賦值操做符
            "error",
            "always"
        ],
        "no-console":[//禁用 console
            "error"
//            { "allow": ["warn", "error"] }
        ],
        "no-constant-condition":"error",//禁止在條件中使用常量表達式
        "no-control-regex":"error",//禁止在正則表達式中使用控制字符
        "no-debugger":"error",//禁用 debugger
        "no-dupe-args":"error",//禁止在 function 定義中出現重複的參數
        "no-dupe-keys":"error",//禁止在對象字面量中出現重複的鍵
        "no-duplicate-case":"error",//禁止重複 case 標籤
        "no-empty":"error",//禁止空塊語句
        "no-empty-character-class":"error",//禁止在正則表達式中出現空字符集
        "no-ex-assign":"error",//禁止對 catch 子句中的異常從新賦值
        "no-extra-boolean-cast":"error",//禁止沒必要要的布爾類型轉換
        "no-extra-parens":"error",//禁止冗餘的括號
        "no-extra-semi":"error",//禁用沒必要要的分號
        "no-func-assign":"error",//禁止對 function 聲明從新賦值
        "no-inner-declarations":"error",//禁止在嵌套的語句塊中出現變量或 function 聲明
        "no-invalid-regexp":"error",//禁止在 RegExp 構造函數中出現無效的正則表達式
        "no-irregular-whitespace":"error",//禁止不規則的空白
        "no-obj-calls":"error",//禁止將全局對象看成函數進行調用
        "no-prototype-builtins":"error",//禁止直接使用 Object.prototypes 的內置屬性
        "no-regex-spaces":"error",//禁止正則表達式字面量中出現多個空格
        "no-sparse-arrays": "error",//禁用稀疏數組
        "no-template-curly-in-string":"error",//禁止在常規字符串中出現模板字面量佔位符語法
        "no-unexpected-multiline":"error",//禁止使用使人困惑的多行表達式
        "no-unreachable":"error",//禁止在 return、throw、continue 和 break 語句後出現不可達代碼
        "no-unsafe-finally":"error",//禁止在 finally 語句塊中出現控制流語句
        "no-unsafe-negation":"error",//禁止對關係運算符的左操做數使用否認操做符
        "use-isnan":"error",//要求調用 isNaN()檢查 NaN
        "valid-jsdoc":"error",//強制使用有效的 JSDoc 註釋
        "valid-typeof":"error",//強制 typeof 表達式與有效的字符串進行比較
        /**
        **最佳實踐
        **/
        "accessor-pairs":"error",//強制getter/setter成對出如今對象中
        "array-callback-return":"error",//強制數組方法的回調函數中有 return 語句
        "block-scoped-var":"error",//把 var 語句看做是在塊級做用域範圍以內
        "class-methods-use-this":"error",//強制類方法使用 this
        "complexity":"error"//限制圈複雜度
        .....
    }

(2)eslint-plugin-vue中的規則

'rules': {

        /* for vue */

        // 禁止重複的二級鍵名

        // @off 不必限制

        'vue/no-dupe-keys': 'off',

        // 禁止出現語法錯誤

        'vue/no-parsing-error': 'error',

        // 禁止覆蓋保留字

        'vue/no-reservered-keys': 'error',

        // 組件的 data 屬性的值必須是一個函數

        'vue/no-shared-component-data': 'off',

        // 禁止 <template> 使用 key 屬性

        'vue/no-template-key': 'off',

        // render 函數必須有返回值

        'vue/require-render-return': 'error',

        // prop 的默認值必須匹配它的類型

        'vue/require-valid-default-prop': 'off',

        // 計算屬性必須有返回值

        'vue/return-in-computed-property': 'error',

        // template 的根節點必須合法

        'vue/valid-template-root': 'error',

        // v-bind 指令必須合法

        'vue/valid-v-bind': 'error',

        // v-cloak 指令必須合法

        'vue/valid-v-cloak': 'error',

        // v-else-if 指令必須合法

        'vue/valid-v-else-if': 'error',

        // v-else 指令必須合法

        'vue/valid-v-else': 'error',

        // v-for 指令必須合法

        'vue/valid-v-for': 'error',

        // v-html 指令必須合法

        'vue/valid-v-html': 'error',

        // v-if 指令必須合法

        'vue/valid-v-if': 'error',

        // v-model 指令必須合法

        'vue/valid-v-model': 'error',

        // v-on 指令必須合法

        'vue/valid-v-on': 'error',

        // v-once 指令必須合法

        'vue/valid-v-once': 'error',

        // v-pre 指令必須合法

        'vue/valid-v-pre': 'error',

        // v-show 指令必須合法

        'vue/valid-v-show': 'error',

        // v-text 指令必須合法

        'vue/valid-v-text': 'error',
        
        //
        // 最佳實踐
        //
        // @fixable html 的結束標籤必須符合規定
        // @off 有的標籤沒必要嚴格符合規定,如 <br> 或 <br/> 都應該是合法的

        'vue/html-end-tags': 'off',

        // 計算屬性禁止包含異步方法

        'vue/no-async-in-computed-properties': 'error',

        // 禁止出現難以理解的 v-if 和 v-for

        'vue/no-confusing-v-for-v-if': 'error',

        // 禁止出現重複的屬性

        'vue/no-duplicate-attributes': 'error',

        // 禁止在計算屬性中對屬性修改

        'vue/no-side-effects-in-computed-properties': 'off',

        // 禁止在 <textarea> 中出現 {{message}}

        'vue/no-textarea-mustache': 'error',

        // 組件的屬性必須爲必定的順序

        'vue/order-in-components': 'error',

        // <component> 必須有 v-bind:is

        'vue/require-component-is': 'error',

        // prop 必須有類型限制

        'vue/require-prop-types': 'off',

        // v-for 指令的元素必須有 v-bind:key

        'vue/require-v-for-key': 'error',
        
        //
        // 風格問題
        //
        // @fixable 限制自定義組件的屬性風格
        // @off 不必限制

        'vue/attribute-hyphenation': 'off',

        // html 屬性值必須用雙引號括起來

        'vue/html-quotes': 'error',

        // @fixable 沒有內容時,組件必須自閉和

        'vue/html-self-closing': 'off',

        // 限制每行容許的最多屬性數量

        'vue/max-attributes-per-line': 'off',

        // @fixable 限制組件的 name 屬性的值的風格

        'vue/name-property-casing': 'off',

        // @fixable 禁止出現連續空格

        // 'vue/no-multi-spaces': 'error',

        // @fixable 限制 v-bind 的風格

        'vue/v-bind-style': 'off',

        // @fixable 限制 v-on 的風格

        'vue/v-on-style': 'off',

        // 定義了的 jsx element 必須使用

        'vue/jsx-uses-vars': 'error'

    }

(3)eslint-plugin-react中的規則

/**
        **react規則
        **/
        "react/boolean-prop-naming": ["error", { "rule": "^is[A-Z]([A-Za-z0-9]?)+" }],//bool類型的props強制固定命名
        "react/button-has-type": ["error", {"reset": false}],//強制按鈕的type屬性必須是"button","submit","reset"三者之一
        "react/default-props-match-prop-types": [2, { "allowRequiredDefaults": false }],//強制全部defaultProps有對應的non-required PropType
        "react/destructuring-assignment": [1, "always"],//強制將props,state,context解構賦值
        "react/display-name": [1, { "ignoreTranspilerName": false }],//react組件中強制定義displayName
        "react/forbid-component-props": [1],//禁止在自定義組件中使用(className, style)屬性
        "react/forbid-dom-props": [1, { "forbid": ["style"] }],//禁止在dom元素上使用禁止的屬性
        "react/forbid-elements": [1, { "forbid": ["button"] }],//禁止某些元素用於其餘元素
        "react/forbid-prop-types": [1],//禁止某些propTypes屬性類型
        "react/no-access-state-in-setstate":"error",//禁止在setState中使用this.state
        "react/no-children-prop":[1],//不要把Children當作屬性
        "react/no-string-refs":[1],//不要使用string類型的ref
        "react/no-unused-state":[1],//不要在state中定義未使用的變量
        //.....
        "react/jsx-no-undef": [1, { "allowGlobals": false }],//不容許使用未聲明的變量
        "react/jsx-key":[1]//遍歷使用key
相關文章
相關標籤/搜索