eslint / prettier 检查格式配置、husky / lint-staged 强制校验

eslint / prettier 检查格式配置

eslint 和 prettier 区别

eslint(包括其他一些 lint 工具)的主要功能包含代码格式的校验,代码质量的校验。而 Prettier 只是代码格式的校验(并格式化代码),不会对代码质量进行校验。代码格式问题通常指的是:单行代码长度、tab长度、空格、逗号表达式等问题。而代码质量问题指的是:未使用变量、三等号、全局变量声明等问题。

对 Prettier(或 Eslint) 进行配置:

  • 根目录创建 .prettierrc.js / .eslintrc.js 文件,能够写入 YML、JSON 的配置格式,并且支持 .yaml/.yml/.json/.js 后缀;
  • 在 package.json 中新建 prettier / eslintConfig 属性。

一些规则的配置

'off': 表示关掉,
'wran': 表示发出警告
'error': 表示发出错误

/*对应的数字是 */
0:表示关掉
1:表示发出警告
2:表示发出错误

"always": 总是开启
"never": 从不开启

vue 实例

安装

yarn add -D @vue/cli-plugin-eslint babel-eslint eslint eslint-config-prettier eslint-plugin-prettier eslint-plugin-vue
module.exports = {
  root: true,
  extends: ["eslint:recommended", "plugin:vue/essential", "plugin:prettier/recommended"],
  parser: "vue-eslint-parser",
  parserOptions: {
    parser: "babel-eslint",
    sourceType: "module",
    allowImportExportEverywhere: true
  },
  env: {
    browser: true,
    node: true,
    es6: true
  },
  globals:{ // 全局变量
    "store":false,
    "Vue":true,
    "Vuex":true
  },
  plugins: ["prettier"],
  rules: {
    "prettier/prettier": [ // 内部配置 prettier
      1,
      {
        semi: false, // 格式化不加分号
        printWidth: 200, // 一行的字符数,如果超过会进行换行,默认为80
        singleQuote: false, // 字符串是否使用单引号,默认为false,使用双引号
        trailingComma: "none", // 是否使用尾逗号,有三个可选值"<none|es5|all>"
        bracketSpacing: true, // 对象大括号直接是否有空格,默认为true,效果:{ foo: bar }
        jsxBracketSameLine: true // JSX 标签闭合位置,默认false,换行闭合
      } // prettier 配置项
    ],
    semi: [1, "never"]
    // 公共 rules 配置
  }
};

react 实例

安装

yarn add -D babel-eslint eslint eslint-config-prettier eslint-plugin-prettier eslint-config-react-app eslint-plugin-react-hooks eslint-plugin-react prettier

配置 autoFix

"fix": "eslint --fix --ext .js,.ts,.tsx --ignore-path .gitignore src/"
module.exports = {
  root: true,
  extends: ["react-app", "eslint:recommended", "plugin:react/recommended", "plugin:prettier/recommended"],
  parserOptions: {
    parser: "babel-eslint",
    sourceType: "module",
    allowImportExportEverywhere: true
  },
  env: {
    browser: true,
    node: true,
    es6: true
  },
  plugins: ["prettier", "react-hooks"],
  rules: {
    "prettier/prettier": [
      1,
      {
        semi: false, // 格式化不加分号
        printWidth: 200, // 一行的字符数,如果超过会进行换行,默认为80
        singleQuote: false, // 字符串是否使用单引号,默认为false,使用双引号
        trailingComma: "none", // 是否使用尾逗号,有三个可选值"<none|es5|all>"
        bracketSpacing: true, // 对象大括号直接是否有空格,默认为true,效果:{ foo: bar }
        jsxBracketSameLine: true, // JSX 标签闭合位置,默认false,换行闭合
      }
    ],
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn",
    "react/jsx-tag-spacing": 1, // 总是在自动关闭的标签前加一个空格,正常情况下也不需要换行
    "jsx-quotes": 1,
    "react/jsx-closing-bracket-location": 1,  // 遵循JSX语法缩进/格式
    "react/jsx-boolean-value": 1, // 如果属性值为 true, 可以直接省略
    "react/no-string-refs": 1,  // 总是在Refs里使用回调函数
    "react/self-closing-comp": 1, // 对于没有子元素的标签来说总是自己关闭标签
    "react/sort-comp": 1,  // 按照具体规范的React.createClass 的生命周期函数书写代码
    "react/jsx-pascal-case": 1, // React模块名使用帕斯卡命名,实例使用骆驼式命名
    "react/display-name": 1,
    semi: [2, "never"]
  }
};

公共 rules 配置

完整 .eslintrc.js 规则
  rules: {
    "no-useless-escape": 0, // 禁用不必要的转义
    semi: [2, "never"], // 语句强制分号结尾
    quotes: [2, "double"], //建议使用单引号
    "no-inner-declarations": [0, "both"], //不建议在{}代码块内部声明变量或函数
    "no-extra-boolean-cast": 0, // 多余的感叹号转布尔型
    "no-extra-semi": 2, // 多余的分号
    "no-extra-parens": 2, // 多余的括号
    "no-empty": 0, // 空代码块
    "no-use-before-define": [2, "nofunc"], // 使用前未定义
    complexity: [2, 20], // 圈复杂度大于20 警告
    "space-before-blocks": [0, "always"], // 不以新行开始的块{前面要有2空格
    "space-before-function-paren": [0, "always"], // 函数定义时括号前面有2空格
    "spaced-comment": 0, // 注释风格 2空格什么的
    "space-infix-ops": 2, // 中缀操作符周围 有2空格
    "space-in-parens": [0, "never"], // 小括号里面要不要有空格
    radix: 0, // parseInt必须指定第二个参数
    "operator-linebreak": [0, "before"], // 换行时运算符在行尾还是行首,可选值"<after|before|none>"
    // "one-var-declaration-per-line": 2, // 单行声明
    "max-len": [0, 200, 2], // 字符串最大长度
    "key-spacing": [2, { beforeColon: false, afterColon: true }], // 对象字面量中冒号的前后空格
    indent: [0, 2], // 缩进风格
    "no-multiple-empty-lines": [1, { max: 2 }], // 空行最多不能超过2行
    "no-multi-str": 2, // 字符串不能用\换行
    "no-mixed-spaces-and-tabs": [2, false], // 禁止混用tab和空格
    "no-console": 1, // 禁止使用console
    "no-const-assign": 2, // 禁止修改const声明的变量

    //常见错误
    "comma-dangle": [2, "never"], // 定义数组或对象最后多余的逗号
    "no-debugger": 2, // debugger 调试代码未删除
    "no-constant-condition": 2, // 常量作为条件
    "no-dupe-args": 2, // 参数重复
    "no-dupe-keys": 2, // 对象属性重复
    "no-duplicate-case": 2, // case重复
    "no-empty-character-class": 2, // 正则无法匹配任何值
    "no-invalid-regexp": 2, // 无效的正则
    "no-func-assign": 2, // 函数被赋值
    "valid-typeof": 2, // 无效的类型判断
    "no-unreachable": 2, // 不可能执行到的代码
    "no-unexpected-multiline": 2, // 行尾缺少分号可能导致一些意外情况
    "no-sparse-arrays": 2, // 数组中多出逗号
    "no-shadow-restricted-names": 2, // 关键词与命名冲突
    "no-undef": 0, // 变量未定义
    "no-unused-vars": 0, // 变量定义后未使用 jsx 处理不了……
    "no-cond-assign": 2, // 条件语句中禁止赋值操作
    "no-native-reassign": 2, // 禁止覆盖原生对象

    //代码风格优化
    "no-else-return": 0, // 在else代码块中return,else是多余的
    "no-multi-spaces": 2, // 不允许多个空格
    "block-scoped-var": 0, // 变量定义后未使用
    "consistent-return": 0, // 函数返回值可能是不同类型
    "accessor-pairs": 2, // object gettertter方法需要成对出现
    "dot-location": [2, "property"], // 换行调用对象方法  点操作符应写在行首
    "no-lone-blocks": 2, // 多余的{}嵌套
    "no-labels": 2, // 无用的标记
    "no-extend-native": 2, // 禁止扩展原生对象
    "no-floating-decimal": 2, // 浮点型需要写全 禁止.2 或 2.写法
    "no-loop-func": 2, // 禁止在循环体中定义函数
    "no-new-func": 2, // 禁止new Function(...) 写法
    "no-self-compare": 2, // 不允与自己比较作为条件
    "no-sequences": 2, // 禁止可能导致结果不明确的逗号操作符
    "no-throw-literal": 2, // 禁止抛出一个直接量 应是Error对象
    "no-return-assign": [2, "always"], // 不允return时有赋值操作
    "no-redeclare": [0, { builtinGlobals: true }], // 不允许重复声明
    "no-unused-expressions": [0, { allowShortCircuit: true, allowTernary: true }], // 未使用的表达式
    "no-useless-call": 2, // 无意义的函数call或apply
    "no-useless-concat": 2, // 无意义的string concat
    "no-void": 2, // 禁用void
    "no-with": 2, // 禁用with
    "no-warning-comments": [2, { terms: ["fixme", "any other term"], location: "anywhere" }], // 标记未写注释
    curly: [2, "all"] // if、else、while、for代码块用{}包围
  }

完整 .prettierrc.js 规则

也可单独在 .prettierrc.js 内配置

// .eslintrc.js
...
rules: {
  "prettier/prettier": 2
  ...
}
// .prettierrc.js
module.exports = {
  semi: false, // 行位是否使用分号,默认为true
  eslintIntegration: true, // 开启 eslint 支持
  printWidth: 100, // 一行的字符数,如果超过会进行换行,默认为80
  tabWidth: 2, // 一个tab代表几个空格数,默认为80
  useTabs: false, // 是否使用tab进行缩进,默认为false,表示用空格进行缩减
  singleQuote: false, // 字符串是否使用单引号,默认为false,使用双引号
  trailingComma: "none", // 是否使用尾逗号,有三个可选值"<none|es5|all>"
  bracketSpacing: true, // 对象大括号直接是否有空格,默认为true,效果:{ foo: bar }
  jsxBracketSameLine: false, // JSX 标签闭合位置,默认false,换行闭合
  arrowParens: "avoid", // 箭头函数参数括号,默认avoid,能省略就省略,可选值"<avoid|always>"
  parser: "babel" // 代码的解析引擎
};

husky / lint-staged 强制校验

安装

yarn add -D husky lint-staged

使用

  // package.json
  
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "src/**/*.{js,json,vue}": [
      "vue-cli-service lint",
      "git add"
    ]
  },

在运行 git commit 时候,自动会先去运行 vue-cli-service lint 格式化代码,再运行 git add 添加代码。这两步都通过后才会提交代码。如果任何一步失败,则会停止提交。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章