背景
在VSCode(Visual Studio Code)中,用Prettier或Beautify格式化后的JS代碼,會被ESLint檢查報錯。
即使禁用了ESLint,在編譯運行時(npm run dev)也會報錯。其實不是語法錯誤,只是沒有符合ESLint預設的規則。
解決方法
1.安裝Vetur、ESlint、Prettier等插件。
2.File -> Preferences -> Setting,點擊右上角的Open Settings (JSON)按鈕,用文本模式編輯設置選項。
3.在花括號內的末尾加入以下代碼:
// vscode默認啟用了根據文件類型自動設置tabsize的選項 "editor.detectIndentation": false, // 重新設定tabsize "editor.tabSize": 2, // 每次保存的時候自動格式化 "editor.formatOnSave": true, // 每次保存的時候將代碼按eslint格式進行修復 "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, // 在函數名和后面的括號之間加個空格 "javascript.format.insertSpaceBeforeFunctionParenthesis": true, // 每次保存的時候將代碼按eslint格式進行修復,新版用editor.codeActionsOnSave "eslint.autoFixOnSave": true, // 添加vue支持 "eslint.validate": [ "html", "javascript", "javascriptreact", "language": "vue" ], // 讓prettier使用eslint的代碼格式進行校驗(新版缺少該屬性) "prettier.eslintIntegration": true, // 使用單引號替代雙引號 "prettier.singleQuote": true, // 去掉代碼結尾的分號 "prettier.semi": false, // 按用戶習慣填寫(這里舉例用js-beautify-html) "vetur.format.defaultFormatter.html": "js-beautify-html", // 讓vue中的js按編輯器自帶的ts格式進行格式化 "vetur.format.defaultFormatter.js": "vscode-typescript", "vetur.format.defaultFormatterOptions": { "js-beautify-html": { "wrap_attributes": "force-aligned" } }, // [選填]用於格式化stylus的選項, 需要先安裝Manta's Stylus Supremacy插件 /* "stylusSupremacy.insertColons": false, //是否插入冒號 "stylusSupremacy.insertSemicolons": false, //是否插入分號 "stylusSupremacy.insertBraces": false, //是否插入大括號 "stylusSupremacy.insertNewLineAroundImports": false, //import之后是否換行 "stylusSupremacy.insertNewLineAroundBlocks": false //兩個選擇器中是否換行 */
* 注意1:由於是在末尾追加選項,所以需要在原有的最后一個選項后面加上逗號“,”,否則會報錯。
* 注意2:有可能會有選項與原有選項重復了,需要刪減重復選項,否則會報警告。
簡便方法
直接安裝Prettier ESLint插件。
