ESLint 与 Prettier 的爱恨纠葛

283 阅读2分钟

先说说 Prettier

Prettier

侧重于代码书写规范,配合vscode(Prettier插件),在文件保存时或者失焦时格式化代码

prettier.io/docs/en/opt…

{
    "tabWidth": 4,
    "printWidth": 120,
    "singleQuote": true,
    "eslintIntegration": true,
    "trailingComma": "none"
}

vscode配置

image.png

再说说 ESLint

ESLint

侧重于代码语法规范,配合husky(package.json), 在git commit时进行 语法校验(参看下文 husky && lint-staged )

cn.eslint.org/docs/user-g…

{
    //默认情况下,ESLint 会在所有父级目录里寻找配置文件,一直到根目录。
    //设置此项会停止在父级目录查找,仅在当前目录查找。
    "root": true,
    //注意,在使用自定义解析器时,为了让 ESLint 在处理非 ECMAScript 5 特性时正常工作,配置属性 `parserOptions` 仍然是必须的。解析器会被传入 `parserOptions`,但是不一定会使用它们来决定功能特性的开关。
    "parserOptions": {
         //ESLint 默认使用[Espree](https://github.com/eslint/espree)作为其解析器
         //以下解析器与 ESLint 兼容:
         //[Esprima](https://www.npmjs.com/package/esprima)
         //[Babel-ESLint](https://www.npmjs.com/package/babel-eslint) - 一个对[Babel](https://babeljs.io/)解析器的包装,使其能够与 ESLint 兼容。
         //[@typescript-eslint/parser](https://www.npmjs.com/package/@typescript-eslint/parser) - 将 TypeScript 转换成与 estree 兼容的形式,以便在ESLint中使用。
        "parser": "babel-eslint",
        //默认设置为 3,5(默认),
        //可使用 6、7、8、9 或 10 指定ECMAScript 版本。
        //也可用 2015(同 6),2016(同 7),或 2017(同 8)或 2018(同 9)或 2019 (same as 10)
        "ecmaVersion": 6,
        //`"script"` (默认) 或 `"module"`(如果你的代码是 ECMAScript 模块)。
        "sourceType": "module" 
    },
    "env": {
        "browser": true,
        "commonjs": true,
        "es6": true
    },
    "extends": ["plugin:vue/base"],
    "plugins": ["vue"],
    "rules": {
        // enable additional rules
        "indent": ["error", 4], //于prettier重复
        "linebreak-style": ["error", "unix"], //于prettier重复
        "quotes": ["error", "double"], //于prettier重复
        "semi": ["error", "always"], //于prettier重复

        // override default options for rules from base configurations
        "comma-dangle": ["error", "always"], //于prettier重复
        "no-cond-assign": ["error", "always"], //于prettier重复

        // disable rules from base configurations
        "no-console": "off",
    }
}

vscode(eslint插件)会在编码时,依据.eslintrc.json,实时提示代码语法错误,

image.png

husky && lint-staged

在git commit前 进行代码校验

  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "src/**/*.{js,jsx}": [
      "eslint --fix",
      "git add"
    ]
  },

但如果文件过多,会导致eslint校验时间过久,解决方案 --cache

eslint --fix  --cache --cache-location \".eslintcache\""

.eslintcache文件不需要提交,解决方案:

.gitignore

node_modules/.cache/.eslintcache

再一起说说

Prettier 和 eslint

pettier与eslint一起使用,它们之间又有重复的地方,如何解决? 解决方案:

参考文章:

prettier官网:prettier.io

eslint官网:cn.eslint.org

eslint与prettier区别:www.zzjtnb.com/blog/detail…

vscode配置保存格式化:www.digitalocean.com/community/t…

配置husky:www.jianshu.com/p/b297376da…