Why use EditorConfig?

May 30, 2021

EditorConfig, as the name suggests, is a configuration for text editors. It helps to achieve consistency in code style among the developers working on the same codebase across different editors. Instead of arguing about tab and space, let EditorConfig take care of it. 😇

Is it similar to Prettier? 🤔

Yes and no. Prettier is an excellent code formatter that formats the code that is already written. We need to run a command or some shortcuts mapped to format our code. But unlike Prettier, EditorConfig sets the editor settings to already formatted style. EditorConfig comes handier when randomly creating a new file and starting to write code (more on this at the end).

This does not mean that we should stop using Prettier. Learn more on why we should use all three - Eslint, Prettier, and EditorConfig together in a project over here.

Setup

Yes, we can create .editorconfig file in every project and define the properties but it is good to have a .editorconfig in home directory for global use (just for personal preference 😛). I have created the file with the following properties in home directory:

# top-most EditorConfig file
root = true

[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = tab

[*.txt]
indent_style = tab
indent_size = 4

[*.py]
indent_style = space
indent_size = 4

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

[*.{diff,md}]
trim_trailing_whitespace = false

[*.{config}]
indent_size = 2

How does it work?

When opening a file, EditorConfig plugins look for a file named .editorconfig in the directory of the opened file and in every parent directory. A search for .editorconfig files will stop if the root filepath is reached or an EditorConfig file with root=true is found. EditorConfig respects the global personal preferences as long as it is not overridden by any local config file.

So, if we want to inherit the properties from the parent .editorconfig in the directory tree, we need to make sure that root is set to false. EditorConfig respects our global personal preferences as long as it is not overridden by any local config file.

Also, a plugin is needed to make it work.

We can find plugins for other editors on EditorConfig’s homepage.

After installing the right plugin for our editor and defining properties in .editorconfig file, we are ready to write some code.

Now when we create a new file, everything is already in format, such as tab size, indent style (tab or spaces), and other properties that we have defined in .editorconfig.

For example: if we need to write a python script, we can simply create a file with .py extension and no more need to worry about things like the 4 spaces indentation. It’s already there. We just start coding.