eslint+prettier

前言

使用eslint+prettier好處:

  • 避免運行時因格式問題報錯
  • 方便團隊合作,代碼風格統一
1.建立項目

利用Vue-cli3建立Vue項目時,一定要選上Linter/Formatter,然后選擇 ESLint + Prettier


2.安裝vscode插件

首先在vscode中安裝如下三個插件:

  • eslint
  • vetur
  • prettier
3.配置
  • .eslintrc.js(根目錄下找)


    注:代碼縮進不是4個空格報錯。

  • .prettierrc
    在文件根目錄下創建.prettierrc對prettier格式化進行自定義規則設置,以下為我添加的規則
{
 /* 單引號包含字符串 */
 "singleQuote": true,
 /* 不添加末尾分號 */
 "semi": false,
 /* 在對象屬性添加空格 */
 "bracketSpacing": true,
 /* 優化html閉合標簽不換行的問題 */
 "htmlWhitespaceSensitivity": "ignore",
 /* 只有一個參數的箭頭函數的參數是否帶圓括號(默認avoid) */
 "arrowParens": "avoid"
}
  • .editorconfig
    只需配置一個 .editorconfig 文件,在其中設置好要遵守的代碼規范,放在項目的根目錄下,就能夠在幾乎所有的主流 IDE 和編輯器中復用了,可以將 .editorconfig 文件也提交到版本控制系統中,就不需要針對不同 IDE 和編輯器再單獨進行設置了
    vscode sublimeText 需要安裝 EditorConfig 插件。

其工作原理是:當你在編碼時,EditorConfig 插件會去查找當前編輯文件的所在文件夾或其上級文件夾中是否有 .editorconfig 文件。如果有,則編輯器的行為會與 .editorconfig 文件中定義的一致,并且其優先級高于編輯器自身的設置。

在文件根目錄下創建.editorconfig,內容如下:

root = true

# 對所有文件生效
[*]
charset = utf-8  //文件編碼。可選值(latin1/utf-8/utf-16be/utf-16le)
indent_style = space   //縮進風格為 空格可選值(space/tab)
indent_size = 4 //縮進大小 (一般設置 2 或 4)
end_of_line=lf //換行符格式。(lf 一般用這個/ crlf/ cr)
insert_final_newline=true  //是否在文件的最后插入一個空行 。(true/false)
trim_trailing_whitespace=true //是否刪除行尾的空格。(true/false)

[*.html]
indent_size = 4
max_line_length = 80

# 對后綴名為 md 的文件生效
[*.md]
trim_trailing_whitespace = false

完整版見這里

  • setting.json(vscode中自帶的setting)
{
    "git.path": "E:/Git/bin/git.exe",
    "vetur.validation.template": true,
    "git.autofetch": true,
    "editor.tabSize": 4,
    "eslint.autoFixOnSave": true,
    // "editor.detectIndentation": false,
    "vetur.format.options.tabSize": 4,//四格縮進
    // "vetur.format.styleInitialIndent": true,
    // "vetur.format.options.useTabs": true,
    // "vetur.format.scriptInitialIndent": true,
    "vetur.format.defaultFormatter.html": "js-beautify-html",
    "vetur.format.defaultFormatterOptions": {
        "js-beautify-html": {
            "wrap_attributes": "auto",//屬性不換行
            "end_with_newline": false
        }
        // "prettier": {
        //     // Prettier option here
        //     "semi": false, //要分號
        //     "singleQuote": true //要單引號
        // }
    },
    "gitlens.gitExplorer.files.layout": "list",
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },
    "update.channel": "none",
    "eslint.validate": [
        "javascript",
        "javascriptreact",
        {
          "language": "vue",
          "autoFix": true
        },
        "vue"
    ],
    "window.zoomLevel": 0
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容