摘要:
在團隊開發中,統一的代碼格式是必要的。但是不同開發人員使用的編輯工具可能不同,這樣就造成代碼的differ。今天給大家分享一個很好的方法來使不同的編輯器保持一樣的風格。
不同的編輯器也有設置代碼風格的,例如我們前端人員最喜歡使用的sublime text 2編輯器。你可以在preferences中選擇Settings-User,然后輸入自定義的風格,比如:
{
"default_line_ending": "unix",
"font_size": 14,
"ignored_packages":
[
"Vintage"
],
"tab_size": 4,
"translate_tabs_to_spaces": true
}
今天我們用editorconfig來實現多種編輯器的代碼風格統一。
簡介:
EditorConfig幫助開發人員定義和維護一致的編碼風格在不同的編輯器和IDE。EditorConfig項目包含一個文件格式定義編碼風格和文本編輯器插件的集合。EditorConfig文件易於閱讀並且他們與版本控制器很好地合作。
editorconfig文件:
下面是一個editorconfig文件例子,用於設置Python和JavaScript行尾和縮進風格的配置文件。
# EditorConfig is awesome: http://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) [*.js] 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文件:
當打開一個文件時,EditorConfig
插件會在打開文件的目錄和其每一級父目錄查找.editorconfig
文件,直到有一個配置文件root=true
。EditorConfig
配置文件從上往下讀取,並且路徑最近的文件最后被讀取。匹配的配置屬性按照屬性應用在代碼上,所以最接近代碼文件的屬性優先級最高。
注意:Windows 用戶在項目根目錄創建.editorconfig
文件,可以先創建“.editorconfig.”
文件,系統會自動重名為.editorconfig
。
文件格式:
EditorConfig
文件使用INI格式。斜杠(/
)作為路徑分隔符,#
或者;
作為注釋。EditorConfig
文件使用UTF-8
格式、CRLF
或LF
作為換行符。
通配符:
* | 匹配除/之外的任意字符串 |
** | 匹配任意字符串 |
? | 匹配任意單個字符 |
[name] | 匹配name字符 |
[!name] | 匹配非name字符 |
{s1,s2,s3} | 匹配任意給定的字符串(since 0.11.0) |
屬性:
indent_style: 設置縮進風格,tab或者空格。tab是hard tabs,space為soft tabs。
indent_size: 縮進的寬度,即列數,整數。如果indent_style為tab,則此屬性默認為tab_width。
tab_width: 設置tab的列數。默認是indent_size。
end_of_line: 換行符,lf、cr和crlf
charset: 編碼,latin1
、utf-8
、utf-8-bom
、utf-16be
和utf-16le,不建議使用utf-8-bom。
trim_trailing_whitespace: 設為true
表示會除去換行行首的任意空白字符。
insert_final_newline: 設為true
表明使文件以一個空白行結尾
root: 表明是最頂層的配置文件,發現設為true
時,才會停止查找.editorconfig
文件。
點擊此處查看更多屬性
注意:屬性不區分大小寫
實例:
下面以sublime text為例,測試editorconfig是否起作用。首先需要給sublime安裝EditorConfig插件,然后在項目的根目錄新建文件".editorconfig",內容如下:
# EditorConfig is awesome: <a onclick="javascript:pageTracker._trackPageview('/outgoing/EditorConfig.org');" href="http://EditorConfig.org">http://EditorConfig.org</a> # 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,html,css}] charset = utf-8 # Tab indentation (no size specified) [*.js] indent_style = tab tab_width = 50
我特意將tab的width修改的很大,你可以重新打開編輯器測試下tab。
附錄:
https://github.com/editorconfig?page=1