Writing Clean and Maintainable Code in NestJS
Part 5 of 12
Consistent Coding Style and Linting
Maintaining consistent coding style is crucial for writing clean, readable, and maintainable TypeScript code in NestJS. A well-formatted codebase is easier to collaborate on, review, and debug.
In this guide, we'll cover:
- Why consistency matters
- Setting up ESLint for linting
- Using Prettier for formatting
- Applying TypeScript best practices
- Automating style enforcement with Husky & Git hooks
1. Why Code Consistency Matters
Imagine a project where every developer follows their own style. Some use snake_case
, others use camelCase
, indentation varies, and imports are unordered.
What happens? Code becomes harder to read, review, and maintain.
Benefits of enforcing style rules:
✅ Improves readability
✅ Reduces bugs caused by inconsistent patterns
✅ Speeds up code reviews
✅ Helps onboard new developers faster
🚀 Good code is consistent, not just correct.
2. Setting Up ESLint in NestJS
ESLint is the most powerful linter for TypeScript. It catches potential errors and ensures style consistency.
📌 Install ESLint
Run:
npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
📌 Create .eslintrc.js
Configuration
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
parserOptions: {
project: './tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
rules: {
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
'@typescript-eslint/explicit-function-return-type': 'off',
'prettier/prettier': ['error', { endOfLine: 'auto' }],
},
};
📌 Run ESLint
Check your code with:
npx eslint .
Fix issues automatically:
npx eslint . --fix
3. Enforcing Code Formatting with Prettier
Prettier automatically formats your code, ensuring consistency.
📌 Install Prettier
npm install --save-dev prettier eslint-config-prettier eslint-plugin-prettier
📌 Create .prettierrc
Configuration
{
"singleQuote": true,
"semi": true,
"trailingComma": "all",
"printWidth": 100
}
📌 Format Code with Prettier
Run:
npx prettier --write .
Prettier vs. ESLint:
- ESLint → Finds errors and bad patterns
- Prettier → Formats code style (spacing, quotes, etc.)
🚀 Use both! ESLint handles logic errors, Prettier handles formatting.
4. TypeScript Best Practices for Clean Code
✅ Use Strong Typing Instead of any
❌ Bad:
function processData(data: any) {
return data.value;
}
✅ Good:
function processData(data: { value: string }): string {
return data.value;
}
Why? Strong types prevent unexpected runtime errors.
✅ Consistent Import Order
Sort imports for better organization. Use eslint-plugin-import
:
npm install --save-dev eslint-plugin-import
Add to .eslintrc.js
:
"plugins": ["import"],
"rules": {
"import/order": ["error", { "alphabetize": { "order": "asc" } }]
}
Organized imports:
// ✅ Good import order
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { User } from '../models/user.model';
✅ Follow Consistent Naming Conventions
Use:
- CamelCase for variables & functions:
userName
,getUserData()
- PascalCase for classes:
UserService
- UPPER_CASE for constants:
DEFAULT_TIMEOUT
❌ Bad:
const user_name = 'John'; // Snake case
const GetUserData = () => {}; // Wrong capitalization
✅ Good:
const userName = 'John';
function getUserData() {}
5. Automating Code Style with Husky & Git Hooks
Prevent bad commits by automating linting & formatting before code is pushed.
📌 Install Husky
npx husky-init && npm install
📌 Add Pre-commit Hook
npx husky add .husky/pre-commit "npx lint-staged"
📌 Configure lint-staged
in package.json
"lint-staged": {
"*.ts": [
"eslint --fix",
"prettier --write"
]
}
Now, every commit runs ESLint & Prettier automatically! 🚀
6. Summary: Clean Code Through Consistency
Key Takeaways
✅ Use ESLint to catch errors & enforce best practices
✅ Use Prettier to auto-format code
✅ Follow TypeScript best practices (no any
, sorted imports, clear naming)
✅ Automate checks with Husky & Git hooks
How do you enforce code consistency in your team? Share your thoughts in the comments!