规范代码风格--EditorConfig

299 阅读3分钟

一、为什么要用 .editorconfig ?

在多人合作的项目中,每个人的开发习惯是不同的。以缩进来说,有的人习惯使用 space 键来进行缩进,有的人喜欢用 tab 键,有的人喜欢设置缩进为 4 个空格,有的人喜欢设置为 2 个空格。这样产生的后果就是每个人修改后的代码在格式上总是不统一的,那么提交到 git 上就会代码风格不一致。

在此之前,我一直使用 Eslint 做代码 lint,那么为什么还要使用 .editorconfig 呢?细细想了下,应该有两个方面吧。

  • Eslint 确实包含 .editorconfig 中的一些属性,如缩进等,但并不全部包含,如 .editorconfig 中的 insert_final_newline 属性 Eslint 就没有。Eslint 更偏向于对语法的提示,如定义了一个变量但是没有使用时应该给予提醒。而 .editorconfig 更偏向于代码风格,如缩进等。
  • Eslint 仅仅支持对 js 文件的校验,而 .editorconfig 不光可以检验 js 文件的代码风格,还可以对 .py(python 文件)、.md(markdown 文件)进行代码风格控制。

总结:根据项目需要,Eslint 和 .editorconfig 并不冲突,同时配合使用可以使代码风格更加优雅。

二、使用 .editorconfig

1. 示例 .editorconfig 文件

通用的 .editorconfig 配置文件一般如下所示:


[*]
[*.{js,jsx,ts,tsx,vue}]
# 根目录的配置文件,编辑器会由当前目录向上查找,如果找到 `roor = true` 的文件,则不再查找
root = true

# 匹配全部文件
[*]

indent_style = space                # 空格缩进,可选"space"、"tab"
indent_size = 4                     # 缩进空格为4个
end_of_line = lf                    # 结尾换行符,可选"lf"、"cr"、"crlf"
charset = utf-8                     # 文件编码是 utf-8
trim_trailing_whitespace = true     # 不保留行末的空格
insert_final_newline = true         # 文件末尾添加一个空行
curly_bracket_next_line = false     # 大括号不另起一行
spaces_around_operators = true      # 运算符两遍都有空格
indent_brace_style = 1tbs           # 条件语句格式是 1tbs

[*.js]                              # 对所有的 js 文件生效
quote_type = single                 # 字符串使用单引号

[*.{html,less,css,json}]            # 对所有 html, less, css, json 文件生效
quote_type = double                 # 字符串使用双引号

[package.json]                      # 对 package.json 生效
indent_size = 2                     # 使用2个空格缩进

在上面配置文件中:

  • 第一行 http://editorconfig.org 是 Editorconfig 的官方网站;
  • 第二行 root = true 控制 .editorconfig 是否生效的字段;
  • 其它字段应该注意的有 indent_sizecharset,如果想要了解更多,参阅:.editorconfig详解

测试是否可用:

在项目的 js 文件中使用 tab 键进行缩进,分别修改 indent_size 属性值为 2 和 4,观察是否有变化。如果没有任何变化,说明还没有安装 Editorconfig 插件。

2. Editorconfig 插件

安装 EditorConfig扩展 在vscode里面安装EditorConfig

image.png

该插件的作用是告诉开发工具 ,如 VSCode 自动去读取项目根目录下的 .editorconfig 配置文件,如果没有安装这个插件,光有一个配置文件是无法生效的。

注意

VS code中需要先安装EditorConfig插件,然后(全局或者局部)安装依赖包

npm install -g editorconfig | npm install -D editorconfig

.editorconfig中的配置才会覆盖默认配置生效。