vsCode使用ESLint+Prettier來統一前端代碼風格

vsCode使用ESLint+Prettier來統一前端代碼風格

在寫vue項目中,統一的代碼風格就愈來愈重要 可是關於代碼風格,咱們很難區分誰對誰錯,不一樣的人有不一樣偏好,惟有強制要求才能規避爭論。 因此,團隊關於代碼風格必須遵循兩個基本原則:javascript

  1. 少數服從多數;
  2. 用工具統一風格。

目標是:vsCode使用 Eslint校驗代碼語法,prettier統一格式化代碼,按下保存自動修復eslint錯誤,自動格式化代碼(由於懶~)css

安裝vscode插件

首先,須要安裝 VeturESLintPrettier - Code formatter這三個插件,安裝完重啓下,防止插件不生效。html

另外這裏有個坑, Beautify插件會佔用格式化代碼的快捷鍵,所以會和prettier產生衝突,因此直接禁用掉。前端

vscode插件配置

打開vscode工具的設置,在settings.json中配置vue

配置以下java

"search.followSymlinks": false,
  "search.useIgnoreFiles": false,
  "guides.enabled": false,
  "editor.tabSize": 2,
  "git.confirmSync": false,
  "window.zoomLevel": 0,
  "editor.renderWhitespace": "boundary",
  "editor.cursorBlinking": "smooth",
  "editor.minimap.enabled": true,
  "editor.minimap.renderCharacters": false,
  "window.title": "${dirty}${activeEditorMedium}${separator}${rootName}",
  "editor.codeLens": true,
  // 配置文件關聯,以便啓用對應的提示
  "files.associations": {
    "*.vue": "vue",
    "*.wxss": "css"
  },
  // 配置emmet是否啓用tab展開縮寫
  "emmet.triggerExpansionOnTab": true,
  // 配置emmet對文件類型的支持
  "emmet.syntaxProfiles": {
    "javascript": "jsx",
    "vue": "html",
    "vue-html": "html"
  },
  // 是否開啓eslint檢測
  "eslint.enable": true,
  // 文件保存時是否根據eslint進行格式化
  "eslint.autoFixOnSave": true,
  // eslint配置文件
  "eslint.options": {
    "extensions": [".js", ".vue"]
  },
  // eslint可以識別的文件後綴類型
  "eslint.validate": [
    "javascript",
    {
      "language": "vue",
      "autoFix": true
    },
    "html",
    "vue"
  ],
  "search.exclude": {
    "**/node_modules": true,
    "**/bower_components": true,
    "**/dist": true
  },
 
複製代碼

ESLint 和 Prettier 的衝突修復

因爲須要同時使用prettiereslint,而prettier的一些規則和eslint的一些規則可能存在衝突,例如prettier字符串默認是用雙引號而esLint定義的是單引號的話這樣格式化以後就不符合ESLint規則了。node

因此要解決衝突就須要在Prettier的規則配置裏也配置上和ESLint同樣的規則,直接覆蓋掉,ESLint和Prettier的配置文件內容以下:git

// 格式化快捷鍵(默認):Shift+Alt+F
  // prettier進行格式化時,開啓eslint支持
  "prettier.eslintIntegration": true,
  // 是否使用單引號
  "prettier.singleQuote": true,
   //js-beautify-html格式化配置,屬性強制換行
  "vetur.format.defaultFormatterOptions": {
    "prettier": {
      "semi": false,
      "singleQuote": true
    },
    "js-beautify-html": {
      "wrap_attributes": "force-aligned"
    }
  },
  "prettier.singleQuote": true,
 "prettier.semi": false,
  "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
"vetur.format.defaultFormatter.js": "vscode-typescript",
"leetcode.endpoint": "leetcode-cn",
"[javascript]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
 }
複製代碼

效果預覽

結尾不能有分號。 typescript

最後

參考了不少網上大佬的文章,可是感受這個配置好像還差了哪裏,但又始終不知道問題在哪裏,熱烈歡迎你們交流指教。json

相關文章
相關標籤/搜索