DEV Community

Matsu
Matsu

Posted on

Harmonizing Code Formatting with .editorconfig and Prettier

Have you ever pondered how projects with multiple developers maintain a consistent code style? Enter .editorconfig and Prettier, two tools that streamline code formatting and ensure uniformity across projects.

Embracing .editorconfig
The .editorconfig file serves as a beacon for code consistency. However, merely creating the file isn't enough. To enforce its settings, we need the "EditorConfig for VS Code" plugin, which overrides user/workspace settings with those defined in .editorconfig.

To begin, let's configure our .editorconfig:

root = true

[*]
indent_style = space
indent_size = 2
Enter fullscreen mode Exit fullscreen mode

Here, root = true specifies that the settings apply at the project's root. The [*] wildcard ensures consistency across all files, enforcing a space-based indentation with a size of 2 spaces.

Introducing Prettier
Prettier takes code formatting to the next level, ensuring code readability and consistency. Let's integrate it into our project:

npm i prettier -D
Enter fullscreen mode Exit fullscreen mode

Now, let's add some scripts to our package.json for Prettier:

{
  "scripts": {
    "lint:check": "prettier --check .",
    "lint:fix": "prettier --write ."
  }
}
Enter fullscreen mode Exit fullscreen mode

With lint:check, we identify formatting issues, and lint:fix automatically corrects them. For example:

npm run lint:check

> prettier --check .

Checking formatting...
[warn] pages/index.js
[warn] Code style issues found in the above file. Run Prettier to fix.
Enter fullscreen mode Exit fullscreen mode

And then we use lint:fix:

npm run lint:fix

> prettier --write .

package.json 94ms (unchanged)
pages/index.js 16ms
Enter fullscreen mode Exit fullscreen mode

Here, it shows which files were modified.

Seamless Integration with VSCode
To automate Prettier on file save, configure VSCode as follows:

  • Set Editor: Default Formatter to Prettier - Code formatter;
  • Enable Editor: Format On Save;
  • Set Files: Auto Save to off;

Now, Prettier runs automatically upon saving any file, ensuring consistent formatting throughout the project.

With .editorconfig and Prettier in place, code formatting becomes effortless, promoting collaboration and readability.

Console You Later!

Top comments (0)