这是我参与11月更文挑战的第3天,活动详情查看:2021最后一次更文挑战
问题1. eslint和prettier是什么关系
一篇写的很好的用来理解eslint和prttier的关系的文章
Use Prettier for code formatting concerns, and linters for code-quality concerns
In other words, use Prettier for formatting and linters for catching bugs!
问题2. down下来的项目修改内容后自动格式化后格式变了,全线飘红?
入职文件中推荐的vscode的setting.json文件中,有设置默认格式化工具和文件,意思是啥呢,也就是如果设置了formatOnSave,就会选用我们设置的文件中的格式去格式化(工作区->全局)。用官网文档中的话来说就是You press save and code is formatted。如果我们既没有配置eslint也没有配置prettier,那么formatOnSave是不会有任何格式化的操作的。
"editor.defaultFormatter":"esbenp.prettier-vscode",
"editor.fontSize": 12,
"prettier.tabWidth": 4,
"prettier.singleQuote": true,
"prettier.semi": true,
"prettier.printWidth": 120,
问题3. 那项目中的eslint文件和prettier又是用来干什么的呢?
eslintrc.json是用来配置eslint规则的文件,我们可以单独拎一个这样的文件,也可以直接写在package.json中
-
eslint-config-prettier在使用prettier后,eslint中有些配置就没有必要了,更甚者他们会冲突。因此在这两个配合使用的时候,我们需要使用这个文件
Turns off all rules that are unnecessary or might conflict with Prettier.关掉所有不必要或者可能和prettier冲突的文件 -
eslint-plugin-prettier会调用prettier对你的代码风格进行检查,其原理是先使用prettier对你的代码进行格式化,然后与格式化之前的代码进行对比,如果过出现了不一致,这个地方就会被prettier进行标记。
接下来,我们需要在rules中添加,"prettier/prettier": "error",表示被prettier标记的地方抛出错误信息。
//.eslintrc.js { "plugins": ["prettier"], "rules": { "prettier/prettier": "error" } }借助ESLint的autofix功能,在保存代码的时候,自动将抛出error的地方进行fix。
当你使用 Prettier + ESLint 的时候,其实格式问题两个都有参与,disable ESLint 之后,其实格式的问题已经全部由 prettier 接手了。那我们为什么还要这个 plugin?其实是因为我们期望报错的来源依旧是 ESLint ,使用这个,相当于把 Prettier 推荐的格式问题的配置以 ESLint rules 的方式写入,这样相当于可以统一代码问题的来源
-
合体
有时候
eslint-config-prettier和eslint-plugin-prettier那就变成了我们常见的plugin:prettier/recommended{ "extends": ["plugin:prettier/recommended"] }那么这是什么意思呢,展开来说就是
{ "extends": ["prettier"], "plugins": ["prettier"], "rules": { "prettier/prettier": "error", "arrow-body-style": "off", "prefer-arrow-callback": "off" } } + "extends": ["prettier"] enables the config from eslint-config-prettier, which turns off some ESLint rules that conflict with Prettier. + "plugins": ["prettier"] registers this plugin. + "prettier/prettier": "error" turns on the rule provided by this plugin, which runs Prettier from within ESLint. + "arrow-body-style": "off" + "prefer-arrow-callback": "off" turns off two ESLint core rules that unfortunately are problematic with this plugin – see the next section. -
prettier-lint