1. 程式人生 > 實用技巧 >eslint+prettier 統一程式碼風格

eslint+prettier 統一程式碼風格

有時git clone下來的專案會出現vscode自動儲存和eslint格式衝突的情況,煩躁得很,此處列出配置統一風格。

1.安裝VsCode程式碼外掛

  • Vetur
  • Eslint
  • Prettier - Code formatter

2.配置VsCode

設定-開啟設定(json)

{
    // 控制工作臺中活動欄的可見性。
    "workbench.activityBar.visible": true,
    //主題設定
    // "workbench.colorTheme": "Monokai",
    // 預設編輯器字號
    "editor.fontSize": 14,
    //是否自動換行
    "editor.wordWrap": "on",
    "workbench.editor.enablePreview": false, //開啟檔案不覆蓋
    "search.followSymlinks": false, //關閉rg.exe程序
    "editor.minimap.enabled": false, //關閉迷你圖快速預覽
    "files.autoSave": "onWindowChange", // 切換視窗時自動儲存。
    "editor.lineNumbers": "on", //開啟行數提示
    "editor.quickSuggestions": {
      //開啟自動顯示建議
      "other": true,
      "comments": true,
      "strings": true
    },
    "editor.tabSize": 2, //製表符符號eslint
  
    //.vue檔案template格式化支援,並使用js-beautify-html外掛
    "vetur.format.defaultFormatter.html": "js-beautify-html",
    //js-beautify-html格式化配置,屬性強制換行
    "vetur.format.defaultFormatterOptions": {
      "js-beautify-html": {
        "wrap_attributes": "force-aligned"
      }
    },
    //根據檔案字尾名定義vue檔案型別
    "files.associations": {
      "*.vue": "vue"
    },
    //配置 ESLint 檢查的檔案型別
    "eslint.validate": [
      "javascript",
      "javascriptreact",
      {
        "language": "vue",
        "autoFix": true
      }
    ],
    //儲存時eslint自動修復錯誤
    "eslint.autoFixOnSave": true,
    //儲存自動格式化
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
    }
  }

3.配置專案中得.eslintrc.js

 1 module.exports = {
 2   root: true,
 3   parserOptions: {
 4     parser: 'babel-eslint'
 5   },
 6   env: {
 7     browser: true
 8   },
 9   extends: [
10     // https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
11     // consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
12 'plugin:vue/essential', 13 // https://github.com/standard/standard/blob/master/docs/RULES-en.md 14 'standard' 15 ], 16 // required to lint *.vue files 17 plugins: [ 18 'vue' 19 ], 20 rules: { 21 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', 22 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
23 //強制使用單引號 24 quotes: ['error', 'single'], 25 //強制不使用分號結尾 26 semi: ['error', 'never'] 27 }, 28 }

4.配置專案中得.prettierrc

{
  "eslintIntegration": true, 
  "singleQuote": true,
  "semi": false
}