VS Code(Visual Studio Code)是一款由微软开发的强大且轻量级的代码编辑器,支持多种编程语言,并提供了丰富的扩展插件生态系统。
这里主要介绍如何使用配置 ESLint、Stylelint 等插件来提升开发效率。
1 自动格式化代码
最终要达到的效果是:在对文件保存时自动格式化 Vue、JS/TS、CSS/SCSS 等文件中的代码。
很多文章都提出使用 prettier 来做代码格式化,但在使用过程中发现它有一些局限性。比如:从一个模块中导入多个接口时,用 prettier 格式化时后会一个接口放一行,相当难看(如下图),而且还没法被 ESLint 修复。
这个问题于 2019 年 3 月就在 github 的 issues 中被提出,5 年过去了仍没有解决,遂放弃 prettier 插件,寻找别的解决方案。后来发现 VS Code 自带的格式化工具就挺好,再与 EditorConfig 及其他插件一结合就挺完美的。
在 VS Code 中安装 ESLint、Stylelint、 Vue - Official、EditorConfig for VS Code 插件。
在项目根目录下创建 .editorconfig 文件,填入以下内容:
# 告诉编辑器这是最顶层的(不要再向上找了)
root = true
# All Files
[*]
charset = utf-8 # 设置编码为 utf-8
indent_style = space # 2 个空格的缩进
indent_size = 2
end_of_line = lf # Unix 风格的换行
insert_final_newline = true # 始终在文件末尾插入一个新行
trim_trailing_whitespace = true # 删除行尾空格
max_line_length = 200 # 单行最大宽度
# Markdown 文件
[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
一个项目里可以有多个.editorconfig 分别放置在不同的文件夹中,当 VS Code 这类编辑器打开一个文件时,它会递归检查这个文件所在目录和它的父级文件夹(直到项目根目录或者是是某个文件夹中的 .editorconfig 里标识了 root = true 才会停止)中是否存在 .editorconfig。被打开的文件格式会以距当前文件最近的 .editorconfig 中的内容为准。
在 VS Code 中打开通过快捷键 Crtl + Shift + P ,输入settings.json 打开 settings.json文件。
在 settings.json 中加入以下内容:
{
// 保存时自动格式化
"editor.formatOnSave": true,
// 保存时自动修复错误
"editor.codeActionsOnSave": {
"source.fixAll": "explicit"
},
// 开启对 .vue 等文件的检查修复
"eslint.validate": [
"javascript",
"typescript",
"javascriptreact",
"typescriptreact",
"html",
"vue",
"markdown"
],
// 开启对样式文件的检查修复
"stylelint.validate": [
"css",
"less",
"scss",
"postcss",
"vue",
"html"
],
// 默认使用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"
}
}
2 常用插件
- Auto Close Tag --标签自动闭合
- Auto Rename Tag --标签自动改名
- Bracket Pair Colorizer – 括号高亮
- Live Server – 启动本地的Web服务器
- Git History – 查看 git 提交历史
- One Dark Pro – 比较好看的黑色主题