使用editorconfig配置你的編輯器

摘要:

  在團隊開發中,統一的代碼格式是必要的。可是不一樣開發人員使用的編輯工具可能不一樣,這樣就形成代碼的differ。今天給你們分享一個很好的方法來使不一樣的編輯器保持同樣的風格。javascript

  不一樣的編輯器也有設置代碼風格的,例如咱們前端人員最喜歡使用的sublime text 2編輯器。你能夠在preferences中選擇Settings-User,而後輸入自定義的風格,好比:css

{html

  "default_line_ending": "unix",前端

  "font_size": 14,java

  "ignored_packages":git

  [github

    "Vintage"json

  ],編輯器

  "tab_size": 4,ide

  "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=trueEditorConfig配置文件從上往下讀取,而且路徑最近的文件最後被讀取。匹配的配置屬性按照屬性應用在代碼上,因此最接近代碼文件的屬性優先級最高。

注意:Windows 用戶在項目根目錄建立.editorconfig文件,能夠先建立「.editorconfig.」文件,系統會自動重名爲.editorconfig

文件格式:

  EditorConfig文件使用INI格式。斜槓(/)做爲路徑分隔符,#或者;做爲註釋。EditorConfig文件使用UTF-8格式、CRLFLF做爲換行符。

通配符:

* 匹配除/以外的任意字符串
** 匹配任意字符串
? 匹配任意單個字符
[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: 編碼,latin1utf-8utf-8-bomutf-16beutf-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

相關文章
相關標籤/搜索