Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+362 -267
View File
@@ -1,278 +1,373 @@
---
description: This rule provides comprehensive guidelines for Angular development, covering coding standards, best practices, performance optimization, security considerations, and testing approaches to ensure maintainable, scalable, and high-performing applications.
globs: *.ts,*.html,*.scss,*.css
description: Provides definitive guidelines for modern Angular development (2025), focusing on best practices for code structure, component architecture, state management with signals, performance, and type safety.
globs: **/*.{ts,html}
---
# Angular Best Practices and Coding Standards
# Angular Best Practices
This document outlines comprehensive best practices and coding standards for developing Angular applications. Adhering to these guidelines will promote maintainability, scalability, performance, and security.
This guide outlines the definitive best practices for Angular development, ensuring consistency, maintainability, and optimal performance. Adhere to these rules strictly.
## 1. Code Organization and Structure
### 1.1. Directory Structure Best Practices
- **Feature-based Modules:** Organize your application into feature modules, where each module encapsulates a specific feature or functionality.
- **Shared Module:** Create a `shared` module for commonly used components, directives, pipes, and services.
- **Core Module:** Create a `core` module for application-wide services and singleton instances (e.g., authentication service, configuration service).
- **Lazy-loaded Modules:** Group related features into lazy-loaded modules to improve initial load time.
- **Directory structure example:**
src/
├── app/
│ ├── core/
│ │ ├── core.module.ts
│ │ └── auth.service.ts
│ ├── shared/
│ │ ├── shared.module.ts
│ │ └── components/
│ │ └── ...
│ ├── features/
│ │ ├── dashboard/
│ │ │ ├── dashboard.module.ts
│ │ │ ├── dashboard.component.ts
│ │ │ └── dashboard.component.html
│ │ ├── user-management/
│ │ │ ├── user-management.module.ts
│ │ │ └── ...
│ │ └── ...
│ ├── app.component.ts
│ └── app.module.ts
└── ...
### 1.2. File Naming Conventions
- **Consistent Naming:** Use a consistent naming pattern for all files and symbols, following the `feature.type.ts` convention (e.g., `user.component.ts`, `user.service.ts`).
- **Type Abbreviations:** Use abbreviations for file types (e.g., `component.ts` -> `.component.ts`, `service.ts` -> `.service.ts`, `module.ts` -> `.module.ts`).
- **Descriptive Names:** Use descriptive names that clearly indicate the purpose of the file.
### 1.1 One Concept Per File (SRP)
### 1.3. Module Organization
**Rule:** Each file must contain a single Angular concept (e.g., one component, one directive, one pipe, one service, one interface).
**Explanation:** This enforces the Single Responsibility Principle (SRP), improving modularity, readability, and testability. Exceptions are rare and only for tightly coupled, non-exported elements.
- **Single Responsibility:** Each module should have a single responsibility.
- **Declarations:** Declare components, directives, and pipes within the appropriate module.
- **Imports:** Import only the necessary modules in each module.
- **Exports:** Export components, directives, and pipes that need to be used by other modules.
- **forRoot() pattern:** Use the `forRoot()` pattern for modules that provide singleton services to ensure they are only instantiated once in the application.
**❌ BAD:**
```typescript
// user.model-and-service.ts
export interface User { id: string; name: string; }
### 1.4. Component Architecture
@Injectable({ providedIn: 'root' })
export class UserService {
// ... fetches users
}
```
**✅ GOOD:**
```typescript
// user.model.ts
export interface User { id: string; name: string; }
// user.service.ts
@Injectable({ providedIn: 'root' })
export class UserService {
// ... fetches users
}
```
### 1.2 Consistent Naming Conventions
**Rule:** Follow kebab-case for file names (`feature-name.type.ts`) and PascalCase for class names. Use standard type suffixes.
**Explanation:** Consistent naming makes files easy to locate and understand at a glance.
- **Smart vs. Dumb Components:** Distinguish between smart (container) components that handle data and logic, and dumb (presentational) components that focus on rendering UI.
- **Component Reusability:** Design components for reusability.
- **Input and Output Properties:** Use `@Input()` and `@Output()` properties to pass data and events between components.
- **Change Detection:** Be mindful of change detection strategies (e.g., `OnPush`) to optimize rendering performance.
**❌ BAD:**
```typescript
// MyUserList.component.ts
export class UserListComp { /* ... */ }
### 1.5. Code Splitting Strategies
- **Lazy Loading:** Implement lazy loading for modules to reduce the initial bundle size and improve load time.
- **Route-based Code Splitting:** Split your application into modules based on routes.
- **Feature-based Code Splitting:** Split your application into modules based on features.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns Specific to Angular
- **Dependency Injection (DI):** Use DI to manage dependencies between components and services.
- **Observables:** Use RxJS Observables for handling asynchronous data streams.
- **Services:** Use services for encapsulating reusable business logic.
- **Pipes:** Use pipes for transforming data in templates.
- **Directives:** Use directives for manipulating the DOM.
### 2.2. Recommended Approaches for Common Tasks
- **Data Binding:** Use data binding (`{{ }}`, `[]`, `()`) to synchronize data between the component and the template.
- **Event Handling:** Use event binding (`()`) to handle user interactions.
- **Form Handling:** Use reactive forms or template-driven forms to manage user input.
- **HTTP Requests:** Use the `HttpClient` to make HTTP requests to backend APIs.
### 2.3. Anti-patterns and Code Smells to Avoid
- **Deeply Nested Components:** Avoid deeply nested component hierarchies, which can make it difficult to manage state and events.
- **Large Components:** Break large components into smaller, reusable components.
- **Logic in Templates:** Avoid complex logic in templates; move it to the component class.
- **Direct DOM Manipulation:** Avoid direct DOM manipulation; use Angular's data binding and directives instead.
- **Unnecessary Subscriptions:** Unsubscribe from Observables to prevent memory leaks. Use the `async` pipe in templates to automatically handle subscriptions and unsubscriptions.
### 2.4. State Management Best Practices
- **Choose a State Management Library:** Consider using a state management library like NgRx, Akita, or MobX for complex applications.
- **Centralized State:** Store application state in a central store.
- **Immutability:** Treat state as immutable to simplify change detection and debugging.
- **Actions and Reducers:** Use actions to describe state changes and reducers to update the state.
- **Selectors:** Use selectors to efficiently retrieve data from the store.
### 2.5. Error Handling Patterns
- **Centralized Error Handling:** Implement a centralized error handling mechanism using an `ErrorHandler`.
- **Error Interceptors:** Use HTTP interceptors to handle errors from backend APIs.
- **User-Friendly Error Messages:** Display user-friendly error messages to the user.
- **Logging:** Log errors to a central logging service for debugging and monitoring.
- **Retry mechanism:** Implement retry mechanism for failed requests using RxJS retry operators.
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **Change Detection Optimization:** Use `OnPush` change detection strategy for components that only depend on their input properties.
- **TrackBy Function:** Use the `trackBy` function with `ngFor` to optimize rendering of lists.
- **Virtualization:** Use virtual scrolling for large lists to improve performance.
- **Ahead-of-Time (AOT) Compilation:** Use AOT compilation to compile templates during the build process, improving startup time.
- **Minification and Uglification:** Minify and uglify your code to reduce bundle size.
### 3.2. Memory Management
- **Unsubscribe from Observables:** Unsubscribe from Observables when they are no longer needed to prevent memory leaks.
- **Avoid Circular Dependencies:** Avoid circular dependencies, which can lead to memory leaks.
- **Detach Event Listeners:** Detach event listeners when they are no longer needed.
### 3.3. Rendering Optimization
- **Minimize DOM Manipulation:** Minimize DOM manipulation, as it can be expensive.
- **Use CSS Transforms:** Use CSS transforms instead of modifying layout properties.
- **Debouncing and Throttling:** Use debouncing and throttling to reduce the frequency of event handlers.
### 3.4. Bundle Size Optimization
- **Lazy Loading:** Implement lazy loading for modules to reduce the initial bundle size.
- **Tree Shaking:** Use tree shaking to remove unused code from your bundle.
- **Code Splitting:** Split your application into smaller bundles to improve load time.
- **Image Optimization:** Optimize images to reduce their file size.
- **Vendor Libraries:** Use only necessary vendor libraries, and ensure they are up-to-date for optimized versions.
### 3.5. Lazy Loading Strategies
- **Route-based Lazy Loading:** Load modules when navigating to a specific route.
- **Feature-based Lazy Loading:** Load modules based on feature requirements.
- **Preloading:** Preload modules in the background to improve perceived performance.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and How to Prevent Them
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and avoiding the use of `innerHTML`.
- **Cross-Site Request Forgery (CSRF):** Prevent CSRF attacks by using anti-CSRF tokens.
- **Injection Attacks:** Prevent injection attacks by validating user input and using parameterized queries.
### 4.2. Input Validation
- **Client-Side Validation:** Perform client-side validation to provide immediate feedback to the user.
- **Server-Side Validation:** Perform server-side validation to ensure data integrity.
- **Whitelist Validation:** Use whitelist validation to allow only specific characters or patterns.
### 4.3. Authentication and Authorization Patterns
- **Authentication:** Implement authentication to verify the user's identity.
- **Authorization:** Implement authorization to control access to resources based on the user's roles and permissions.
- **JSON Web Tokens (JWT):** Use JWTs for secure authentication and authorization.
- **OAuth 2.0:** Use OAuth 2.0 for delegating authorization to third-party applications.
### 4.4. Data Protection Strategies
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Hashing:** Hash passwords before storing them in the database.
- **Data Masking:** Mask sensitive data to prevent unauthorized access.
### 4.5. Secure API Communication
- **HTTPS:** Use HTTPS for secure communication between the client and the server.
- **API Keys:** Use API keys to authenticate API requests.
- **Rate Limiting:** Implement rate limiting to prevent abuse of your API.
## 5. Testing Approaches
### 5.1. Unit Testing Strategies
- **Test Driven Development (TDD):** Write tests before writing code.
- **Component Testing:** Test components in isolation using mock data.
- **Service Testing:** Test services in isolation using dependency injection.
- **Pipe Testing:** Test pipes to ensure they transform data correctly.
### 5.2. Integration Testing
- **Module Testing:** Test modules to ensure they integrate correctly.
- **Component Interaction Testing:** Test the interaction between components.
- **HTTP Testing:** Test HTTP requests and responses.
### 5.3. End-to-End Testing
- **User Interface (UI) Testing:** Test the UI to ensure it behaves as expected.
- **Workflow Testing:** Test complete workflows to ensure they function correctly.
- **Cross-Browser Testing:** Test your application in different browsers.
### 5.4. Test Organization
- **Test Directory Structure:** Mirror your source code directory structure in your test directory.
- **Test File Naming:** Use consistent naming conventions for test files (e.g., `user.component.spec.ts`).
- **Test Suites:** Group related tests into test suites.
### 5.5. Mocking and Stubbing
- **Mock Dependencies:** Mock dependencies to isolate units of code for testing.
- **Stub HTTP Requests:** Stub HTTP requests to avoid making actual API calls during testing.
- **Use Mocking Libraries:** Use mocking libraries like Jasmine or Jest to simplify mocking and stubbing.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes Developers Make
- **Forgetting to Unsubscribe from Observables:** Always unsubscribe from Observables to prevent memory leaks.
- **Using `any` Type:** Avoid using the `any` type, as it bypasses type checking.
- **Not Handling Errors:** Handle errors gracefully to prevent unexpected behavior.
- **Ignoring Performance:** Optimize your code for performance from the beginning.
### 6.2. Edge Cases to Be Aware Of
- **Empty Arrays:** Handle empty arrays correctly.
- **Null Values:** Handle null values correctly.
- **Unexpected Input:** Validate user input to prevent unexpected behavior.
### 6.3. Version-Specific Issues
- **Breaking Changes:** Be aware of breaking changes in new versions of Angular and third-party libraries.
- **Deprecated APIs:** Avoid using deprecated APIs.
- **Migration Guides:** Follow migration guides when upgrading to new versions of Angular.
### 6.4. Compatibility Concerns
- **Browser Compatibility:** Test your application in different browsers to ensure compatibility.
- **Device Compatibility:** Test your application on different devices to ensure compatibility.
### 6.5. Debugging Strategies
- **Browser Developer Tools:** Use browser developer tools to debug your code.
- **Logging:** Use logging to track the flow of execution and identify errors.
- **Debugging Tools:** Use debugging tools like VS Code's debugger to step through your code.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
- **VS Code:** Use VS Code as your code editor.
- **Angular CLI:** Use the Angular CLI for scaffolding, building, and deploying your application.
- **Chrome Developer Tools:** Use Chrome Developer Tools for debugging and performance profiling.
### 7.2. Build Configuration
- **Angular CLI Configuration:** Configure your Angular CLI settings in the `angular.json` file.
- **Environment Variables:** Use environment variables to configure your application for different environments.
- **Build Optimization:** Configure your build process to optimize your code for production.
### 7.3. Linting and Formatting
- **ESLint:** Use ESLint to enforce coding standards.
- **Prettier:** Use Prettier to format your code automatically.
- **Husky:** Use Husky to run linters and formatters before committing code.
### 7.4. Deployment Best Practices
- **Continuous Integration/Continuous Deployment (CI/CD):** Use a CI/CD pipeline to automate the build, test, and deployment process.
- **Deployment Environments:** Use different deployment environments for development, testing, and production.
- **CDN:** Use a content delivery network (CDN) to serve static assets.
### 7.5. CI/CD Integration
- **Jenkins:** Use Jenkins for CI/CD.
- **GitHub Actions:** Use GitHub Actions for CI/CD.
- **Azure DevOps:** Use Azure DevOps for CI/CD.
- **GitLab CI:** Use GitLab CI for CI/CD.
By following these best practices and coding standards, you can build robust, maintainable, and scalable Angular applications.
// authservice.ts
export class AuthenticationService { /* ... */ }
```
**✅ GOOD:**
```typescript
// user-list.component.ts
export class UserListComponent { /* ... */ }
// auth.service.ts
export class AuthService { /* ... */ }
```
## 2. Component Architecture
### 2.1 Standalone Components by Default
**Rule:** Always create standalone components, directives, and pipes. Avoid NgModules for new features unless strictly necessary for legacy integration or specific library patterns.
**Explanation:** Standalone components simplify the Angular mental model, reduce boilerplate, and improve tree-shaking.
**❌ BAD:**
```typescript
// app.module.ts
@NgModule({
declarations: [MyComponent],
imports: [CommonModule],
// ...
})
export class AppModule { }
// my.component.ts
@Component({
selector: 'app-my',
template: `<p>My Component</p>`,
styleUrls: ['./my.component.css'],
})
export class MyComponent { }
```
**✅ GOOD:**
```typescript
// my.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common'; // Import dependencies directly
@Component({
selector: 'app-my',
standalone: true, // Always standalone
imports: [CommonModule],
template: `<p>My Component</p>`,
styleUrls: ['./my.component.css'],
})
export class MyComponent { }
```
### 2.2 Prefer `inject` for Dependency Injection
**Rule:** Use the `inject` function for all dependency injection, especially in field initializers. Avoid constructor injection unless required for specific lifecycle hooks or inheritance patterns.
**Explanation:** `inject` offers greater flexibility, better tree-shaking, and allows injection outside of constructors.
**❌ BAD:**
```typescript
import { MyService } from './my.service';
@Component({...})
export class MyComponent {
private myService: MyService;
constructor(myService: MyService) {
this.myService = myService;
}
}
```
**✅ GOOD:**
```typescript
import { inject } from '@angular/core';
import { MyService } from './my.service';
@Component({...})
export class MyComponent {
// Use a private readonly field for injected services
private readonly myService = inject(MyService);
// You can also inject in functions if needed (e.g., providers)
// readonly myOtherService = someFactoryFn(inject(AnotherService));
}
```
## 3. State Management
### 3.1 Prioritize Signals for Component State
**Rule:** Use Angular Signals for all local component state and simple derived state. Reserve RxJS for complex asynchronous data streams, side effects, and inter-component communication.
**Explanation:** Signals provide a reactive, performant, and simpler way to manage state, optimizing change detection automatically.
**❌ BAD:**
```typescript
// Using plain properties and relying on Zone.js for change detection
@Component({...})
export class MyComponent {
count = 0;
items: string[] = [];
addItem(item: string) {
this.items.push(item); // Direct mutation, less reactive
}
}
```
**✅ GOOD:**
```typescript
import { Component, signal, computed } from '@angular/core';
@Component({...})
export class MyComponent {
readonly count = signal(0); // Primitive signal
readonly items = signal<string[]>([]); // Array signal
// Derived state with computed
readonly hasItems = computed(() => this.items().length > 0);
increment() {
this.count.update(value => value + 1);
}
addItem(item: string) {
this.items.update(currentItems => [...currentItems, item]); // Immutable update
}
}
```
### 3.2 RxJS for Asynchronous Streams and Effects
**Rule:** Leverage RxJS for handling HTTP requests, complex event streams, and orchestrating side effects. Always manage subscriptions to prevent memory leaks.
**Explanation:** RxJS is powerful for reactive programming with asynchronous data. Use `toSignal` or `takeUntilDestroyed` for automatic unsubscription.
**❌ BAD:**
```typescript
// Manual subscription management
ngOnInit() {
this.userService.getUsers().subscribe(users => {
this.users = users;
});
}
ngOnDestroy() {
// Forgot to unsubscribe, potential memory leak
}
```
**✅ GOOD:**
```typescript
import { Component, inject, DestroyRef } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop'; // For converting RxJS to Signal
import { UserService } from './user.service';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { tap } from 'rxjs';
@Component({...})
export class MyComponent {
private readonly userService = inject(UserService);
private readonly destroyRef = inject(DestroyRef);
// Convert an RxJS Observable to a Signal, automatically unsubscribes
readonly users = toSignal(this.userService.getUsers(), { initialValue: [] });
// For effects or more complex streams, manage with takeUntilDestroyed
constructor() {
this.userService.someAction$
.pipe(
tap(action => console.log('Action:', action)),
takeUntilDestroyed(this.destroyRef) // Automatic unsubscription
)
.subscribe();
}
}
```
## 4. Performance Considerations
### 4.1 Use Built-in Control Flow
**Rule:** Discontinue the use of structural directives (`*ngIf`, `*ngFor`, `*ngSwitch`). Always use Angular's new built-in control flow syntax.
**Explanation:** The new control flow (`@if`, `@for`, `@switch`) offers improved performance, better type checking, and a more intuitive syntax.
**❌ BAD:**
```html
<!-- Using *ngIf -->
<div *ngIf="isLoading">Loading...</div>
<!-- Using *ngFor -->
<li *ngFor="let item of items; let i = index">{{ item.name }}</li>
```
**✅ GOOD:**
```html
<!-- Using @if -->
@if (isLoading) {
<div>Loading...</div>
} @else {
<div>Data loaded!</div>
}
<!-- Using @for with track -->
@for (item of items; track item.id) {
<li>{{ item.name }}</li>
} @empty {
<p>No items found.</p>
}
```
### 4.2 Always Use `track` Key in `@for`
**Rule:** Always provide a `track` key in `@for` loops. Use a unique, primitive property of the object (e.g., `item.id`). If iterating over primitives, use the value directly.
**Explanation:** The `track` key helps Angular optimize rendering by identifying unique items, preventing unnecessary DOM re-renders and improving performance.
**❌ BAD:**
```html
<!-- Angular will re-render all items if the array reference changes -->
@for (user of users) {
<li>{{ user.name }}</li>
}
```
**✅ GOOD:**
```html
<!-- Optimized re-rendering based on user.id -->
@for (user of users; track user.id) {
<li>{{ user.name }}</li>
}
<!-- For primitive arrays, track the value itself -->
@for (name of names; track name) {
<li>{{ name }}</li>
}
```
## 5. Type Safety
### 5.1 Define Interfaces for Data Structures
**Rule:** Always define TypeScript interfaces or types for all data structures, especially those received from APIs or used in models.
**Explanation:** Interfaces provide strong type checking, improve code readability, and catch errors early.
**❌ BAD:**
```typescript
// Loosely typed data
fetchUsers().subscribe((data: any) => {
console.log(data.users[0].firstName); // Prone to runtime errors
});
```
**✅ GOOD:**
```typescript
export interface User {
id: string;
firstName: string;
lastName: string;
email: string;
}
fetchUsers().subscribe((data: User[]) => {
console.log(data[0].firstName); // Type-safe access
});
```
### 5.2 Default to `readonly` Properties
**Rule:** Declare component properties and injected services as `readonly` where their values are not intended to be reassigned after initialization.
**Explanation:** `readonly` encourages immutability, prevents accidental reassignments, and makes state flow more predictable.
**❌ BAD:**
```typescript
@Component({...})
export class MyComponent {
title = 'My App'; // Can be reassigned anywhere
private myService = inject(MyService); // Can be reassigned
}
```
**✅ GOOD:**
```typescript
@Component({...})
export class MyComponent {
readonly title = 'My App'; // Immutable after initialization
private readonly myService = inject(MyService); // Immutable reference to service
}
```
## 6. Accessibility (A11y)
### 6.1 Leverage Angular Aria and CDK
**Rule:** Integrate Angular Aria and the Component Dev Kit (CDK) for building accessible UI components. Always provide appropriate ARIA attributes and semantic HTML.
**Explanation:** Angular's built-in tools help ensure your applications are usable by everyone, including those with disabilities.
**❌ BAD:**
```html
<!-- Custom button without proper ARIA roles -->
<div (click)="doSomething()">Click Me</div>
```
**✅ GOOD:**
```html
<!-- Semantic button with ARIA attributes for accessibility -->
<button type="button" (click)="doSomething()" aria-label="Perform action">Click Me</button>
<!-- Using CDK for accessible interactions, e.g., cdkMenu -->
<button cdkMenuTrigger>Open Menu</button>
<div cdkMenu>
<button cdkMenuItem>Item 1</button>
</div>
```