EditorConfig

在多人开发的时候,会出现编码风格统一的问题,这时候需要EditorConfig.

EditorConfig简介

EditorConfig帮助开发人员在不同的编辑器和IDE之间定义和维护一致的编码风格。EditorConfig项目由用于定义编码样式的文件格式和一组文本编辑器插件组成,这些编辑器可以读取文件格式并遵守定义的样式。EditorConfig文件易于阅读,并且与版本控制系统配合良好。

示例文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true

# Matches multiple files with brace expansion notation
# Set default charset
[*.{js,py}]
charset = utf-8

# 4 space indentation
[*.py]
indent_style = space
indent_size = 4

# Tab indentation (no size specified)
[Makefile]
indent_style = tab

# Indentation override for all JS under lib directory
[lib/**.js]
indent_style = space
indent_size = 2

# Matches the exact files either package.json or .travis.yml
[{package.json,.travis.yml}]
indent_style = space
indent_size = 2

配置

EditorConfig文件使用INI格式与所使用的格式兼容的Python ConfigParser库。类似于gitignore格式。只有正斜线(/而不是反斜线)用作路径分隔符,而(#)或分号(;)用于注释。

通配符

通配符 说明
* 匹配任何字符串,除了路径分隔符(/)
** 匹配任何字符串
? 匹配任何字符串
[name] 与名称中的任何单个字符匹配
[!name] 匹配任何不在名称中的单个字符
{s1,s2,s3} 匹配任何给定的字符串(以逗号分隔)
{num1..num2} 匹配num1和num2之间的任何整数,其中num1和num2可以是正值或负值

支持的常用属性

属性名 说明
indent_style 缩进使用tab或者space
indent_size 缩进为space时,缩进的字符数
tab_width 缩进为tab时,缩进的宽度
end_of_line 换行符的类型。lf, cr, crlf三种
charset 文件的charset。有以下几种类型:latin1, utf-8, utf-8-bom, utf-16be, utf-16le
trim_trailing_whitespace 是否将行尾空格自动删除
insert_final_newline 是否使文件以一个空白行结尾
root 表明是最顶层的配置文件,发现设为true时,才会停止查找.editorconfig文件

更多属性见https://github.com/editorconfig/editorconfig/wiki/EditorConfig-Properties

编辑器支持

默认支持

编辑器

需插件支持

编辑器

常见的问题

VSCode支持

VSCode默认不支持EditorConfig。
需要在编辑器的插件(Ctrl + Shift + X)安装中 EditorConfig for VS Code,即可支持。

WebStorm支持

WebStorm默认支持EditorConfig文件,需要设置

  • 打开WebStorm > File > settings(快捷键Ctrl + Alt + S)。
  • 找到Editor > Code Style 并点击它,在下面会有一个Enable EditorConfig support,选中复选框。
  • 复选框的后面有一个Export按钮,它是导出editorConfig配置文件,点击确定,可在项目中自动生成一份.editorConfig配置文件。
------本文结束 感谢阅读------