VS Code 擴充推薦 - EditorConfig

Posted on  Aug 11, 2023  in  VS Code , VS Code 擴充推薦  by  Amo Chen  ‐ 3 min read

一樣米養百樣人,每個人喜歡用的編輯器(editor)都不一樣,有些人喜歡用 Vim, 有些人喜歡 Emacs, 有些人則使用 Visual Studio Code(VS Code),個人則是 Vim 與 VS Code 兩棲使用者。

也由於編輯器預設值/設定不一樣,例如有些使用 Tab 縮排,有些用 4 個空格縮排,這種不同編輯器間的差異,會對開發團隊帶來 coding styles 不ㄧ致的問題,而且每個公司一般來說會有各種開發專案,不同開發專案間有不同的 coding styles 是很常見的事,這時如果只是在 README 或開發文件中規定 coding styles 不僅麻煩,也容易造成開發者的困擾。

針對這種問題,目前最好的解決辦法就是使用 EditorConfig ,將 coding styles 設定寫成 .editorconfig 放到各個專案之中,並請每位團隊成員安裝 EditorConfig 擴充(extension/plugin),如此就能讓團隊成員在開啟各種不同專案自動載入不同的 coding styles, 完成一種無縫切換的開發體驗!

本文環境

  • Visual Studio Code

EditorConfig

如前文所述, EditorConfig 是設定編輯器 coding styles 的工具,其優點是能夠跨編輯器,從 PyCharm, Visual Studio(不是 VS Code), GitHub, GitLab 等,都預設支援 EditorConfig, 而不支援的編輯器如 Vim, Emacs, VS Code, eclipse等, EditorConfig 也都提供擴充(extension/plugin)可以安裝,盡其所能的做到超高涵蓋率。

目前也很多知名的開源專案都有使用 EditorConfig, 諸如 React, Grafana, Apache Airflow 等等,足見 EditorConfig 也是知名科技公司或是開發團隊會使用的工具之一。

EditorConfig 使用方法

EditorConfig 的使用方法很簡單,首先要在專案的根目錄建立一個名稱為 .editorconfig 的檔案,舉 Facebook 的 React 專案為例:

接著只要在 .editorconfig 中寫入設定即可,例如:

root = true

[*]
indent_style = space
indent_size = 2

上述的設定的 root = true 代表此 .editorconfig 是最終的設定檔了,如果設定為 false 的話, EditorConfig 會再往外一層繼續尋找 .editorconfig 檔案是否存在,所以一般都是將 .editorconfig 放在專案的根目錄底下,並設定 root = true 就好。

[*] 則代表所有檔案,並且要遵循 indent_style = space 以及 indent_size = 2 的縮排設定,也就是以 2 個空格作為縮排單位。

如果想要針對其他副檔名進行規範的話,舉 Python 為例,可以多設定:

root = true

[*]
indent_style = space
indent_size = 2

[*.py]
indent_style = space
indent_size = 4

或者有多種不同副檔名要使用同一種設定時,舉副檔名 js, ts, json, tsx 為例:

root = true

[*]
indent_style = space
indent_size = 2

[*.py]
indent_style = space
indent_size = 4

[*.{js,ts,json,tsx}]
indent_style = space
indent_size = 2

除了 indent_styleindent_size 之外, EditorConfig 還提供:

  • tab_width 設定 tab 寬度
  • end_of_line 設定行尾特殊符號,設定值為 lf, crcrlf ,分別代表 \n, \r\r\n ,Windows 都是使用 crlf 而 Linux/UNIX 則是使用 lf , 如果團隊中同時存在 Windows 與 Linux/UNIX 使用者,建議要設定 end_of_line
  • charset 設定檔案使用的編碼
  • trim_trailing_whitespace 設定自動移除行尾空白
  • insert_final_newline 設定檔案最後一行為空行,通常 Python PEP8 會要求檔案最後一行為空行,如果是 Python 開發者可以開啟此設定

更多範例與文件說明可以參閱 EditorConfig 官方網站

VS Code 擴充(extension)

設定好之後, VS Code 只要安裝 EditorConfig for VS Code 就能夠自動載入 .editorconfig 相關設定。

如果是先安裝此擴充,但是沒有事先設定好 .editorconfig 的人,也可以在專案資料夾點右鍵選擇 Generate .editorconfig 產生:

總結

Good extension, Happy coding life!

References

EditorConfig

editorconfig/editorconfig-vim: EditorConfig plugin for Vim

EditorConfig for VS Code - Visual Studio Marketplace

FOLLOW US

對抗久坐職業傷害

研究指出每天增加 2 小時坐著的時間,會增加大腸癌、心臟疾病、肺癌的風險,也造成肩頸、腰背疼痛等常見問題。

然而對抗這些問題,卻只需要工作時定期休息跟伸展身體即可!

你想輕鬆改變現狀嗎?試試看我們的 PomodoRoll 番茄鐘吧! PomodoRoll 番茄鐘會根據你所設定的專注時間,定期建議你 1 項辦公族適用的伸展運動,幫助你打敗久坐所帶來的傷害!

贊助我們的創作

看完這篇文章了嗎? 休息一下,喝杯咖啡吧!

如果你覺得 MyApollo 有讓你獲得實用的資訊,希望能看到更多的技術分享,邀請你贊助我們一杯咖啡,讓我們有更多的動力與精力繼續提供高品質的文章,感謝你的支持!