網(wǎng)站SEO做點提升流量象客下載百度極速版免費(fèi)安裝
VS Code(Visual Studio Code)是一款由微軟開發(fā)的強(qiáng)大且輕量級的代碼編輯器,支持多種編程語言,并提供了豐富的擴(kuò)展插件生態(tài)系統(tǒng)。
這里主要介紹如何使用配置 ESLint、Stylelint 等插件來提升開發(fā)效率。
1 自動格式化代碼
最終要達(dá)到的效果是:在對文件保存時自動格式化 Vue、JS/TS、CSS/SCSS 等文件中的代碼。
很多文章都提出使用 prettier 來做代碼格式化,但在使用過程中發(fā)現(xiàn)它有一些局限性。比如:從一個模塊中導(dǎo)入多個接口時,用 prettier 格式化時后會一個接口放一行,相當(dāng)難看(如下圖),而且還沒法被 ESLint 修復(fù)。
這個問題于 2019 年 3 月就在 github 的 issues 中被提出,5 年過去了仍沒有解決,遂放棄 prettier 插件,尋找別的解決方案。后來發(fā)現(xiàn) VS Code 自帶的格式化工具就挺好,再與 EditorConfig 及其他插件一結(jié)合就挺完美的。
在 VS Code 中安裝 ESLint、Stylelint、 Vue - Official、EditorConfig for VS Code 插件。
在項目根目錄下創(chuàng)建 .editorconfig 文件,填入以下內(nèi)容:
# top-most EditorConfig file
root = true# All Files
[*]
charset = utf-8 # Set default charset
indent_style = space # 2 space indentation
indent_size = 2
end_of_line = lf # Unix-style
insert_final_newline = true # newlines with a newline ending every file
trim_trailing_whitespace = true # remove any whitespace characters preceding newline characters
max_line_length = 200 # Forces hard line wrapping after the amount of characters specified# Markdown Files
[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
在 VS Code 中打開通過快捷鍵 Crtl + Shift + P ,輸入settings.json 打開 settings.json文件。
在 settings.json 中加入以下內(nèi)容:
{// 保存時自動格式化"editor.formatOnSave": true,// 保存時自動修復(fù)錯誤"editor.codeActionsOnSave": {"source.fixAll": "explicit"},// 開啟對 .vue 等文件的檢查修復(fù)"eslint.validate": ["javascript","typescript","javascriptreact","typescriptreact","html","vue","markdown"],// 開啟對樣式文件的檢查修復(fù)"stylelint.validate": ["css","less","scss","postcss","vue","html"],// 默認(rèn)使用vscode的css格式化"[css]": {"editor.defaultFormatter": "vscode.css-language-features"},"[scss]": {"editor.defaultFormatter": "vscode.css-language-features"},"[typescript]": {"editor.defaultFormatter": "vscode.typescript-language-features"},"[vue]": {"editor.defaultFormatter": "Vue.volar"}
}