ESLint+Prettier+StyleLint在VSCode的配置与冲突问题

668 阅读3分钟

问题1:是否需要prettier

prettier和eslint的功能很相似,虽然两者有不同的侧重点,但也有很多重复的部分。在排查一个样式的问题时,我反复的去修改prettier和eslint的配置很苦恼,过程中发现有其他人也有类似的苦恼 antfu: 为什么我不用Prettier, 详情的可以进去看看,说的很全,几乎每一点都很赞同,所以我直接把所有与prettier相关的配置和库都删掉了。

  • 网上有n篇关于怎么解决prettier与eslint冲突的文章,再也与自己无关了

问题2:vscode保存触发的自动格式化代码,如使用eslint --fix格式化的代码风格不一致

关联问题:vscode保存时,代码格式化了两次

先上一段vscode setting.json的配置代码,一般大家都会建议如下配置,以使eslint生效,不过有个前提,得先装vscode的Eslint插件,不然不会按照.stylelintrc.cjs配置文件的规则去报错

 "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll": "explicit",
    "source.fixAll.eslint": "explicit",
    "source.fixAll.stylelint": "explicit"
  },

格式化不一致或格式化两次的原因是vscode有自己的格式化规则,该规则与eslint的规则不一致导致的,我们需要做的就是关掉vscode自己的规则。设置 "editor.formatOnSave": false。就这么简单,我看网上有很多关于类似eslint不生效或解决冲突的办法,各种配置setting.json,但我这边只需要这一个false就解决了,或许是vscode以及eslint版本的问题吧,贴下:vscode版本:1.91.1,eslint的npm版本: "eslint": "^8.57.0",

通过这个问题我们还可以看出,vscode是先执行editor.codeActionsOnSave再执行editor.formatOnSave

问题3: vscode保存时,自动格式化css不生效(stylelint不生效)

stylelint是格式化css用的,比如可以让css的属性按照一个良好的顺序排列。 我遇到该问题后的办法是检查setting.json配置添加如下部分

 "stylelint.validate": [
    "css",
    "scss",
    "vue",
    "html"
  ],

顺便说下,我看到很多说eslint需要配eslint.validate或eslint.enable的,可能是老版本需要吧,但我这边并没有那么多配置,下面贴下我全部的setting.json配置

{
  "typescript.tsdk": "./node_modules/typescript/lib",
  "npm.packageManager": "pnpm",
  "editor.tabSize": 2,
  "editor.formatOnSave": false,
  "editor.quickSuggestions": {
    "other": true,
    "comments": true,
    "strings": true
  },
  "editor.codeActionsOnSave": {
    "source.fixAll": "never",
    "source.fixAll.eslint": "explicit",
    "source.fixAll.stylelint": "explicit"
  },
  "stylelint.validate": [
    "css",
    "scss",
    "vue",
    "html"
  ],
  "files.eol": "\n",
  "search.exclude": {
    "**/node_modules": true,
    "**/*.log": true,
    "**/*.log*": true,
    "**/bower_components": true,
    "**/dist": true,
    "**/elehukouben": true,
    "**/.git": true,
    "**/.gitignore": true,
    "**/.svn": true,
    "**/.DS_Store": true,
    "**/.idea": true,
    "**/.vscode": false,
    "**/yarn.lock": true,
    "**/tmp": true,
    "out": true,
    "dist": true,
    "node_modules": true,
    "CHANGELOG.md": true,
    "examples": true,
    "res": true,
    "screenshots": true,
    "yarn-error.log": true,
    "**/.yarn": true
  },
  "files.exclude": {
    "**/.cache": true,
    "**/.editorconfig": true,
    "**/.eslintcache": true,
    "**/bower_components": true,
    "**/.idea": true,
    "**/tmp": true,
    "**/.git": true,
    "**/.svn": true,
    "**/.hg": true,
    "**/CVS": true,
    "**/.DS_Store": true
  },
  "files.watcherExclude": {
    "**/.git/objects/**": true,
    "**/.git/subtree-cache/**": true,
    "**/.vscode/**": true,
    "**/node_modules/**": true,
    "**/tmp/**": true,
    "**/bower_components/**": true,
    "**/dist/**": true,
    "**/yarn.lock": true
  }
}