Member-only story
How to Write a Custom ESLint Rule
Consistent code layout is crucial for readability and maintainability in large projects. One specific guideline that many teams prefer is ensuring a clean separation between class methods by requiring a certain number of blank lines. This article will guide you through implementing a custom ESLint rule to enforce two blank lines before each method in a class when there are multiple methods, and one blank line if the class contains only a single method
What This Rule Does
The rule, named two-blank-lines-before-class-methods, ensures:
1. Two blank lines precede each method in a class containing multiple methods.
2. One blank line precedes the only method in a class with a single method.
3. It automatically fixes violations by inserting the required blank lines.
This rule is particularly useful for projects that prioritize clean, consistent spacing in class definitions.
Configuration
The rule can be added to your ESLint configuration as follows:
"rules": {
"@nx/workspace-two-blank-lines-before-class-methods": "error"
}
Implementation
Here’s how the rule is implemented: