1. 程式人生 > 實用技巧 >vsCode程式碼格式設定

vsCode程式碼格式設定

ESlint:是用來統一JavaScript程式碼風格的工具,不包含css、html等

背景

近來研究前端,然後一直在百度上找VScode格式化(ESlint)的外掛,結果找了半天都不靠譜。目前沒有一個可以格式化html、css、符合ESlint的js、vue的外掛,所以自己東拼西湊加實踐找到解決方法。

一、安裝外掛

1)ESlint:javascript程式碼檢測工具,可以配置每次儲存時格式化js,但每次儲存只格式化一點點,你得連續按住Ctrl+S好幾次,才格式化好,自行體會~~
2)vetur:可以格式化html、標準css(有分號 、大括號的那種)、標準js(有分號 、雙引號的那種)、vue檔案,

但是!格式化的標準js檔案不符合ESlint規範,會給你加上雙引號、分號等,像這樣

3)Prettier - Code formatter:只關注格式化,並不具有eslint檢查語法等能力,只關心格式化檔案(最大長度、混合標籤和空格、引用樣式等),包括JavaScript · Flow · TypeScript · CSS · SCSS · Less · JSX · Vue · GraphQL · JSON · Markdown
4)Manta's Stylus Supremacy:

格式化stylus的外掛(不用就不裝),因為vetur會把css格式化有分號 、大括號的那種,此外掛會把css格式化成stylus風格,像這樣

二、配置settings.json資訊

File->Preference->Settings【也可以快捷鍵 ctr + ,(window系統) 直接開啟】

現在看到的是介面配置模式,點選右上角的大括號(如下圖),可以開啟 settings.json 檔案。

貼上以下程式碼,儲存即可

把程式碼貢獻一下:

複製程式碼

{
    // vscode預設啟用了根據檔案型別自動設定tabsize的選項
    "editor.detectIndentation": false,
    // 重新設定tabsize
    "editor.tabSize": 4,
    // #值設定為true時,每次儲存的時候自動格式化;值設定為false時,程式碼格式化請按shift+alt+F
    "editor.formatOnSave": false,
    // #每次儲存的時候將程式碼按eslint格式進行修復
    "eslint.autoFixOnSave": true,
    // 新增 vue 支援
    "eslint.validate": [
        "javascript",
        "javascriptreact",
        {
            "language": "vue",
            "autoFix": true
        }
    ],
    //  #讓prettier使用eslint的程式碼格式進行校驗
    "prettier.eslintIntegration": true,
    //  #去掉程式碼結尾的分號
    "prettier.semi": false,
    //  #使用帶引號替代雙引號
    "prettier.singleQuote": true,
    "prettier.tabWidth": 4,
    //  #讓函式(名)和後面的括號之間加個空格
    "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
    // #這個按使用者自身習慣選擇
    "vetur.format.defaultFormatter.html": "js-beautify-html",
    // #讓vue中的js按"prettier"格式進行格式化
    "vetur.format.defaultFormatter.js": "prettier",
    "vetur.format.defaultFormatterOptions": {
        "js-beautify-html": {
            // #vue元件中html程式碼格式化樣式
            "wrap_attributes": "force-aligned", //也可以設定為“auto”,效果會不一樣
            "wrap_line_length": 200,
            "end_with_newline": false,
            "semi": false,
            "singleQuote": true
        },
        "prettier": {
            "semi": false,
            "singleQuote": true
        }
    },
    "[jsonc]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    // 格式化stylus, 需安裝Manta's Stylus Supremacy外掛
    "stylusSupremacy.insertColons": false, // 是否插入冒號
    "stylusSupremacy.insertSemicolons": false, // 是否插入分號
    "stylusSupremacy.insertBraces": false, // 是否插入大括號
    "stylusSupremacy.insertNewLineAroundImports": false, // import之後是否換行
    "stylusSupremacy.insertNewLineAroundBlocks": false,
    "prettier.useTabs": true,
    "files.autoSave": "off",
    "explorer.confirmDelete": false,
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[json]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "diffEditor.ignoreTrimWhitespace": false // 兩個選擇器中是否換行
}

從此直接 Ctrl+S 就能一鍵格式化了。