mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +08:00
Add comprehensive MDC files for various technologies and frameworks
Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including: - AI/ML libraries (PyTorch, TensorFlow, scikit-learn) - Backend frameworks (Django, FastAPI, Express, Spring Boot) - Frontend frameworks (React, Vue, Angular) - Cloud platforms (AWS, Azure, GCP) - Development tools (Docker, Kubernetes, Terraform) - State management libraries - UI component libraries - Web technologies and APIs Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
@@ -0,0 +1,278 @@
|
||||
---
|
||||
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}
|
||||
---
|
||||
# Angular Best Practices and Coding Standards
|
||||
|
||||
This document outlines comprehensive best practices and coding standards for developing Angular applications. Adhering to these guidelines will promote maintainability, scalability, performance, and security.
|
||||
|
||||
## 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.3. Module Organization
|
||||
|
||||
- **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.
|
||||
|
||||
### 1.4. Component Architecture
|
||||
|
||||
- **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.
|
||||
|
||||
### 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.
|
||||
@@ -0,0 +1,204 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices for developing Qwik applications, covering code organization, performance, security, testing, and common pitfalls. It aims to guide developers in writing maintainable, efficient, and secure Qwik code.
|
||||
globs: **/*.ts?(x)
|
||||
---
|
||||
# Qwik Library Best Practices
|
||||
|
||||
This document outlines the best practices for developing Qwik applications. Adhering to these guidelines will help you write maintainable, efficient, and secure code.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- **Directory Structure:**
|
||||
- `src/`: Contains the source code of your application.
|
||||
- `components/`: Reusable UI components.
|
||||
- `routes/`: Defines the application's routes and pages. Use the file system routing for easy setup. Each file under `routes` will become a route based on the filename.
|
||||
- `services/`: Contains business logic and data fetching services.
|
||||
- `utils/`: Utility functions and helpers.
|
||||
- `styles/`: Global styles and themes.
|
||||
- `types/`: Type definitions used throughout the application.
|
||||
- `public/`: Static assets like images, fonts, and favicons.
|
||||
- `vite.config.ts`: Vite configuration file.
|
||||
- `tsconfig.json`: TypeScript configuration file.
|
||||
- `.eslintrc.js`: ESLint configuration file.
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Components: `ComponentName.tsx` (e.g., `MyButton.tsx`).
|
||||
- Services: `serviceName.ts` (e.g., `userService.ts`).
|
||||
- Utilities: `utilityName.ts` (e.g., `dateUtils.ts`).
|
||||
- Styles: `componentName.css` or `componentName.module.css`.
|
||||
- Routes: Filename dictates the route path (e.g., `index.tsx` for `/`, `about.tsx` for `/about`).
|
||||
|
||||
- **Module Organization:**
|
||||
- Group related components, services, and utilities into modules.
|
||||
- Use `index.ts` files to re-export members from a module for cleaner imports.
|
||||
- Keep modules focused and avoid creating large, monolithic modules.
|
||||
|
||||
- **Component Architecture:**
|
||||
- Favor small, reusable components.
|
||||
- Use a component-based architecture for building UIs.
|
||||
- Separate concerns: presentational components and container components.
|
||||
- Presentational components: Focus on rendering UI elements based on props.
|
||||
- Container components: Handle data fetching, state management, and business logic.
|
||||
- Use Qwik's `component$` and `use*` APIs for creating and managing components.
|
||||
|
||||
- **Code Splitting Strategies:**
|
||||
- Use Qwik's automatic code splitting capabilities.
|
||||
- Ensure routes are lazily loaded by their nature in Qwik.
|
||||
- For larger components or modules, consider manually triggering lazy loading.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
- **Design Patterns:**
|
||||
- **Composition:** Build complex components by composing smaller, reusable components.
|
||||
- **Provider Pattern:** Use Context to share state or services across multiple components.
|
||||
- **Hooks:** Use Qwik's `use*` hooks to manage state, effects, and other side effects.
|
||||
- **Factories:** For complex object creation, consider using factory functions.
|
||||
|
||||
- **Recommended Approaches:**
|
||||
- Use Qwik's state management features (`useStore`, `useSignal`) for managing component state.
|
||||
- Use Qwik City's routing capabilities for defining routes and navigation.
|
||||
- Use Qwik's optimizer and server rendering for performance.
|
||||
|
||||
- **Anti-patterns and Code Smells:**
|
||||
- **Large Components:** Avoid creating overly large components. Break them down into smaller, more manageable pieces.
|
||||
- **Tight Coupling:** Reduce dependencies between components and modules.
|
||||
- **Mutating Props:** Never directly modify props passed to a component.
|
||||
- **Global State Abuse:** Avoid using global state excessively. Prefer component-level state management.
|
||||
- **Ignoring Server Rendering:** Ensure your components are server-renderable for initial page load performance.
|
||||
|
||||
- **State Management Best Practices:**
|
||||
- Use Qwik's `useStore` for reactive state management.
|
||||
- Consider `useSignal` for simpler reactive values.
|
||||
- Avoid direct DOM manipulation; rely on Qwik's component rendering.
|
||||
|
||||
- **Error Handling Patterns:**
|
||||
- Use `try...catch` blocks to handle errors gracefully.
|
||||
- Display user-friendly error messages.
|
||||
- Log errors for debugging and monitoring.
|
||||
- Consider using error boundary components to prevent entire application crashes.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- Use Qwik's optimizer to minimize bundle size and improve performance.
|
||||
- Leverage server rendering to improve initial page load time.
|
||||
- Optimize images and other assets.
|
||||
- Use Qwik's built-in lazy loading features.
|
||||
|
||||
- **Memory Management:**
|
||||
- Avoid memory leaks by properly cleaning up resources.
|
||||
- Unsubscribe from subscriptions and event listeners when components unmount.
|
||||
|
||||
- **Rendering Optimization:**
|
||||
- Use `track` property in `useStore` to selectively trigger updates.
|
||||
- Memoize expensive computations using `useComputed$()`
|
||||
- Avoid unnecessary re-renders by ensuring component props are stable.
|
||||
|
||||
- **Bundle Size Optimization:**
|
||||
- Use code splitting to reduce the initial bundle size.
|
||||
- Remove unused code and dependencies.
|
||||
- Use tree shaking to eliminate dead code.
|
||||
|
||||
- **Lazy Loading Strategies:**
|
||||
- Use Qwik's built-in lazy loading features for components and routes.
|
||||
- Consider using dynamic imports for loading modules on demand.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
- **Common Vulnerabilities:**
|
||||
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user inputs and using Qwik's built-in escaping mechanisms.
|
||||
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection by using tokens and validating requests.
|
||||
- **Injection Attacks:** Prevent SQL injection and other injection attacks by using parameterized queries and escaping user inputs.
|
||||
|
||||
- **Input Validation:**
|
||||
- Validate all user inputs on both the client and server sides.
|
||||
- Use appropriate data types and formats.
|
||||
- Sanitize user inputs to prevent XSS attacks.
|
||||
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use a secure authentication mechanism, such as OAuth or JWT.
|
||||
- Implement proper authorization checks to ensure users only have access to the resources they are authorized to access.
|
||||
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS to secure communication between the client and server.
|
||||
- Implement proper access controls to protect data from unauthorized access.
|
||||
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API requests.
|
||||
- Validate API responses.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Write unit tests for individual components, services, and utilities.
|
||||
- Use a testing framework like Jest or Vitest.
|
||||
- Mock dependencies to isolate units under test.
|
||||
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to verify interactions between different parts of the application.
|
||||
- Test the integration of components, services, and routes.
|
||||
|
||||
- **End-to-end Testing:**
|
||||
- Write end-to-end tests to verify the entire application flow.
|
||||
- Use a testing framework like Playwright or Cypress.
|
||||
- Test user interactions and navigation.
|
||||
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories based on the type of test.
|
||||
- Use descriptive test names.
|
||||
- Follow a consistent testing style.
|
||||
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing to isolate units under test.
|
||||
- Mock external dependencies, such as APIs and databases.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
- **Frequent Mistakes:**
|
||||
- Forgetting to use Qwik's `component$` for creating components.
|
||||
- Not using `use*` hooks for managing state and effects.
|
||||
- Over-reliance on `globalThis`.
|
||||
|
||||
- **Edge Cases:**
|
||||
- Handling errors during server rendering.
|
||||
- Dealing with different browser environments.
|
||||
- Managing application state across multiple pages.
|
||||
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of breaking changes between Qwik versions.
|
||||
- Consult the Qwik changelog for migration instructions.
|
||||
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure your application is compatible with different browsers and devices.
|
||||
- Use polyfills to support older browsers.
|
||||
|
||||
- **Debugging Strategies:**
|
||||
- Use browser developer tools for debugging.
|
||||
- Use Qwik's built-in debugging features.
|
||||
- Log errors and warnings.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- Visual Studio Code with the Qwik extension.
|
||||
- Node.js and npm.
|
||||
- A modern web browser.
|
||||
|
||||
- **Build Configuration:**
|
||||
- Use Vite for building and bundling Qwik applications.
|
||||
- Configure Vite to optimize the build for production.
|
||||
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint and Prettier for linting and formatting code.
|
||||
- Configure ESLint and Prettier to follow Qwik's coding style.
|
||||
|
||||
- **Deployment Best Practices:**
|
||||
- Deploy your application to a serverless environment, such as Netlify or Vercel.
|
||||
- Configure your server to serve static assets efficiently.
|
||||
- Use a CDN to cache static assets.
|
||||
|
||||
- **CI/CD Integration:**
|
||||
- Integrate your application with a CI/CD pipeline.
|
||||
- Automate testing, building, and deployment.
|
||||
@@ -0,0 +1,169 @@
|
||||
---
|
||||
description: Enforces Next.js best practices for code organization, performance, security, and maintainability. This rule provides guidelines for structuring Next.js projects, optimizing performance, and avoiding common pitfalls.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
- **General Principles**
|
||||
- **Use Static Generation (SSG) or Incremental Static Regeneration (ISR) where possible.** SSG offers the best performance by pre-rendering pages at build time. ISR allows you to update static pages after build time.
|
||||
- **Optimize Images.** Use `next/image` for automatic image optimization, including resizing, format conversion, and lazy loading.
|
||||
- **Utilize API Routes.** Create API endpoints using the `pages/api` directory for serverless functions.
|
||||
- **Follow a Consistent Component Structure.** Maintain a clear and predictable component structure for reusability and maintainability.
|
||||
- **Implement Code Splitting.** Split your code into smaller chunks using dynamic imports (`next/dynamic`) to improve initial load time.
|
||||
- **Lazy Load Non-Essential Resources.** Defer loading of resources that are not critical for the initial page load.
|
||||
- **Prefer Functional Programming and Immutable Data Structures.** This can improve code readability and reduce the risk of bugs.
|
||||
- **Handle Errors Robustly.** Implement comprehensive error handling and logging throughout your application.
|
||||
|
||||
- **Code Organization and Structure**
|
||||
- **Directory Structure:**
|
||||
- `pages/`: Contains page components and API routes.
|
||||
- `components/`: Stores reusable UI components.
|
||||
- `styles/`: Holds global and component-specific CSS/SCSS modules.
|
||||
- `public/`: Static assets like images, fonts, and favicons.
|
||||
- `lib/` or `utils/`: Utility functions and helper modules.
|
||||
- `contexts/`: React Context providers for state management.
|
||||
- `hooks/`: Custom React hooks.
|
||||
- `types/` or `interfaces/`: TypeScript type definitions.
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive names for components and files (e.g., `ProductCard.tsx`, `useAuth.js`).
|
||||
- Employ camelCase for JavaScript filenames and PascalCase for component filenames.
|
||||
- Use kebab-case for CSS class names.
|
||||
- **Module Organization:**
|
||||
- Group related components and utilities into modules (e.g., `components/auth`, `utils/api`).
|
||||
- Export modules using named exports for better discoverability and tree-shaking.
|
||||
- **Component Architecture:**
|
||||
- Favor small, reusable components.
|
||||
- Use composition over inheritance.
|
||||
- Separate concerns by creating presentational (UI) and container (logic) components.
|
||||
- Utilize the `children` prop to create flexible and reusable components.
|
||||
- **Code Splitting Strategies:**
|
||||
- Use dynamic imports (`next/dynamic`) for large components or modules that are not critical for the initial page load.
|
||||
- Split code based on routes or user interactions.
|
||||
- Utilize Next.js's automatic code splitting.
|
||||
|
||||
- **Common Patterns and Anti-patterns**
|
||||
- **Design Patterns:**
|
||||
- **Higher-Order Components (HOCs):** For cross-cutting concerns like authentication or data fetching.
|
||||
- **Render Props:** For sharing logic between components.
|
||||
- **Compound Components:** For creating complex UI elements with implicit state sharing.
|
||||
- **Recommended Approaches:**
|
||||
- **Data Fetching:** Use `getStaticProps`, `getServerSideProps`, or `getInitialProps` (legacy) for data fetching.
|
||||
- **State Management:** Consider using React Context, Zustand, Redux Toolkit, or Jotai for managing application state.
|
||||
- **Routing:** Utilize `next/link` for client-side navigation and `next/router` for programmatic routing.
|
||||
- **Anti-patterns:**
|
||||
- **Direct DOM Manipulation:** Avoid manipulating the DOM directly; use React's state and props instead.
|
||||
- **Global CSS Conflicts:** Use CSS Modules or CSS-in-JS to prevent style conflicts.
|
||||
- **Over-fetching Data:** Fetch only the data that is needed by the component.
|
||||
- **Unnecessary Re-renders:** Optimize component rendering using `React.memo` or `useMemo`.
|
||||
- **State Management Best Practices:**
|
||||
- Choose a state management solution that fits the complexity of your application.
|
||||
- Centralize state that is shared between multiple components.
|
||||
- Use immutable data structures to avoid unexpected side effects.
|
||||
- Use selectors to derive data from the state.
|
||||
- **Error Handling Patterns:**
|
||||
- Use `try...catch` blocks to handle errors gracefully.
|
||||
- Implement error boundaries to prevent crashes in production.
|
||||
- Log errors to a monitoring service for debugging.
|
||||
- Display user-friendly error messages.
|
||||
|
||||
- **Performance Considerations**
|
||||
- **Optimization Techniques:**
|
||||
- **Minimize JavaScript Bundle Size:** Remove unused code, use tree-shaking, and compress your code.
|
||||
- **Optimize Third-Party Libraries:** Choose lightweight alternatives or lazy-load libraries.
|
||||
- **Cache API Responses:** Use caching to reduce the load on your API servers.
|
||||
- **Use a CDN:** Serve static assets from a Content Delivery Network (CDN).
|
||||
- **Memory Management:**
|
||||
- **Avoid Memory Leaks:** Clean up event listeners and timers when components unmount.
|
||||
- **Use Efficient Data Structures:** Choose data structures that are appropriate for the task.
|
||||
- **Rendering Optimization:**
|
||||
- **Use `React.memo`:** Prevent unnecessary re-renders of components.
|
||||
- **Virtualize Long Lists:** Render only the visible items in a long list to improve performance.
|
||||
- **Defer Expensive Calculations:** Use `useMemo` or `useCallback` to memoize expensive calculations.
|
||||
- **Bundle Size Optimization:**
|
||||
- **Analyze Bundle Size:** Use tools like `webpack-bundle-analyzer` to identify large dependencies.
|
||||
- **Remove Unused Dependencies:** Remove dependencies that are not being used.
|
||||
- **Use Code Splitting:** Split your code into smaller chunks to reduce initial load time.
|
||||
- **Lazy Loading Strategies:**
|
||||
- **Lazy Load Images:** Use `next/image` with the `lazy` loading prop.
|
||||
- **Lazy Load Components:** Use `next/dynamic` to lazy load components.
|
||||
- **Lazy Load Data:** Fetch data only when it is needed.
|
||||
|
||||
- **Security Best Practices**
|
||||
- **Common Vulnerabilities:**
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks.
|
||||
- **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to protect against CSRF attacks.
|
||||
- **SQL Injection:** Use parameterized queries or an ORM to prevent SQL injection attacks.
|
||||
- **Authentication and Authorization Vulnerabilities:** Implement secure authentication and authorization mechanisms.
|
||||
- **Input Validation:**
|
||||
- **Validate all user input:** Ensure that the input is of the expected type and format.
|
||||
- **Sanitize user input:** Remove or escape potentially harmful characters.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- **Use a secure authentication provider:** Consider using a third-party authentication provider like Auth0 or Firebase Authentication.
|
||||
- **Implement role-based access control (RBAC):** Restrict access to resources based on user roles.
|
||||
- **Use JSON Web Tokens (JWTs) for authentication:** JWTs are a secure and stateless way to authenticate users.
|
||||
- **Data Protection Strategies:**
|
||||
- **Encrypt sensitive data:** Encrypt data at rest and in transit.
|
||||
- **Use HTTPS:** Use HTTPS to encrypt communication between the client and server.
|
||||
- **Store passwords securely:** Use a strong hashing algorithm to store passwords.
|
||||
- **Secure API Communication:**
|
||||
- **Use API keys or tokens for authentication:** Require API keys or tokens for all API requests.
|
||||
- **Rate limit API requests:** Prevent abuse by limiting the number of requests that can be made from a single IP address.
|
||||
- **Validate API requests:** Ensure that the API requests are valid and authorized.
|
||||
|
||||
- **Testing Approaches**
|
||||
- **Unit Testing Strategies:**
|
||||
- **Test individual components and functions in isolation.**
|
||||
- **Use mocking and stubbing to isolate dependencies.**
|
||||
- **Write tests for different scenarios and edge cases.**
|
||||
- **Integration Testing:**
|
||||
- **Test the interaction between multiple components or modules.**
|
||||
- **Test data flow and state management.**
|
||||
- **End-to-End Testing:**
|
||||
- **Test the entire application flow from the user's perspective.**
|
||||
- **Use tools like Cypress or Playwright for end-to-end testing.**
|
||||
- **Test Organization:**
|
||||
- **Keep tests close to the code they are testing.**
|
||||
- **Use a consistent naming convention for tests.**
|
||||
- **Organize tests into logical groups.**
|
||||
- **Mocking and Stubbing:**
|
||||
- **Use mocking to replace external dependencies with mock objects.**
|
||||
- **Use stubbing to replace functions with predefined return values.**
|
||||
|
||||
- **Common Pitfalls and Gotchas**
|
||||
- **Frequent Mistakes:**
|
||||
- **Forgetting to handle errors.**
|
||||
- **Over-complicating state management.**
|
||||
- **Not optimizing images.**
|
||||
- **Not securing API routes.**
|
||||
- **Edge Cases:**
|
||||
- **Handling different screen sizes and devices.**
|
||||
- **Dealing with slow network connections.**
|
||||
- **Handling unexpected user input.**
|
||||
- **Version-Specific Issues:**
|
||||
- **Breaking changes in Next.js updates.**
|
||||
- **Compatibility issues with third-party libraries.**
|
||||
- **Compatibility Concerns:**
|
||||
- **Browser compatibility issues.**
|
||||
- **Accessibility issues.**
|
||||
- **Debugging Strategies:**
|
||||
- **Use the browser's developer tools to debug JavaScript code.**
|
||||
- **Use the Next.js devtools extension for debugging Next.js applications.**
|
||||
- **Use logging to track the flow of execution and identify errors.**
|
||||
|
||||
- **Tooling and Environment**
|
||||
- **Recommended Development Tools:**
|
||||
- **VS Code:** A popular code editor with excellent support for JavaScript and TypeScript.
|
||||
- **ESLint:** A linter for identifying and fixing code style issues.
|
||||
- **Prettier:** A code formatter for automatically formatting code.
|
||||
- **Webpack Bundle Analyzer:** A tool for analyzing the size of your JavaScript bundles.
|
||||
- **Build Configuration:**
|
||||
- **Configure Webpack to optimize your code for production.**
|
||||
- **Use environment variables to configure your application for different environments.**
|
||||
- **Linting and Formatting:**
|
||||
- **Use ESLint and Prettier to enforce a consistent code style.**
|
||||
- **Configure your editor to automatically format code on save.**
|
||||
- **Deployment Best Practices:**
|
||||
- **Deploy your application to a platform like Vercel or Netlify.**
|
||||
- **Use environment variables to configure your application for production.**
|
||||
- **Monitor your application for errors and performance issues.**
|
||||
- **CI/CD Integration:**
|
||||
- **Use a CI/CD pipeline to automate the build, test, and deployment process.**
|
||||
- **Integrate your linting and formatting tools into your CI/CD pipeline.**
|
||||
@@ -0,0 +1,203 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices for developing React applications with Mobx, covering code organization, performance, testing, and security considerations. It aims to guide developers in building robust and maintainable applications using React-Mobx.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
# React-Mobx Best Practices
|
||||
|
||||
This document outlines best practices for developing React applications with Mobx. Following these guidelines will help you build robust, maintainable, and performant applications.
|
||||
|
||||
## 1. Core Principles
|
||||
|
||||
- **Model observable state:** Define the source of truth in your Mobx stores and make them observable.
|
||||
- **Use derived state (computed properties):** Derive data from your observable state using `computed` properties to avoid unnecessary re-renders and ensure data consistency.
|
||||
- **Embrace mutability:** Mobx encourages direct mutation of observable state within actions.
|
||||
- **Use strict mode:** Enforce predictable state changes by using `use strict` or enabling strict mode in Mobx to ensure all state modifications happen within actions.
|
||||
- **Keep actions in MobX stores:** Encapsulate state mutations within Mobx actions to ensure data integrity and simplify debugging.
|
||||
- **Prefer class vs object syntax:** Use class syntax for creating stores as it offers better structure, inheritance, and maintainability.
|
||||
- **Inject store rather than importing:** Use dependency injection (e.g., React Context) to provide stores to components instead of importing them directly to improve testability and reduce tight coupling.
|
||||
|
||||
## 2. Code Organization and Structure
|
||||
|
||||
- **Directory Structure:**
|
||||
- `/src`:
|
||||
- `/components`: React components (presentational and container components).
|
||||
- `/stores`: Mobx stores containing observable state and actions.
|
||||
- `/models`: Data models and types definitions.
|
||||
- `/services`: API clients and other services.
|
||||
- `/utils`: Utility functions.
|
||||
- `/hooks`: Custom React hooks.
|
||||
- `/constants`: Application-wide constants.
|
||||
- `/test`: Unit, integration, and end-to-end tests.
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Components: `ComponentName.jsx` or `ComponentName.tsx`
|
||||
- Stores: `StoreName.store.js` or `StoreName.store.ts`
|
||||
- Models: `ModelName.model.js` or `ModelName.model.ts`
|
||||
- Services: `ServiceName.service.js` or `ServiceName.service.ts`
|
||||
- Hooks: `useHookName.js` or `useHookName.ts`
|
||||
|
||||
- **Module Organization:**
|
||||
- Group related components, stores, and models into modules.
|
||||
- Use clear and descriptive module names.
|
||||
- Avoid circular dependencies between modules.
|
||||
|
||||
- **Component Architecture:**
|
||||
- **Presentational Components:** Responsible for rendering UI and receiving data via props.
|
||||
- **Container Components:** Connect presentational components to Mobx stores and manage state updates.
|
||||
- Use the `observer` decorator/function from `mobx-react-lite` to make components react to observable changes.
|
||||
|
||||
- **Code Splitting Strategies:**
|
||||
- Use React's `lazy` and `Suspense` components for lazy loading routes or components.
|
||||
- Implement route-based code splitting to load only necessary code for the current route.
|
||||
- Consider using `dynamic imports` for on-demand loading of modules.
|
||||
|
||||
## 3. Common Patterns and Anti-patterns
|
||||
|
||||
- **Design Patterns:**
|
||||
- **Observer Pattern:** Mobx uses the observer pattern to automatically update components when observable state changes.
|
||||
- **Dependency Injection:** Use React Context to inject stores into components, making them more testable and reusable.
|
||||
- **Provider Pattern:** Use a Provider component to make stores available to the component tree.
|
||||
|
||||
- **Recommended Approaches:**
|
||||
- **Form Handling:** Use Mobx to manage form state and validation.
|
||||
- **Asynchronous Operations:** Use Mobx actions to handle asynchronous operations and update the state accordingly.
|
||||
- **List Rendering:** Optimize list rendering using `key` props and `React.memo`.
|
||||
|
||||
- **Anti-patterns and Code Smells:**
|
||||
- **Modifying State Outside Actions:** Always modify observable state within Mobx actions to ensure data consistency.
|
||||
- **Deeply Nested Observables:** Avoid deeply nested observable objects as they can impact performance.
|
||||
- **Computing Data in Components:** Use `computed` properties in stores to derive data instead of computing it directly in components.
|
||||
- **Over-Observing:** Only observe the specific parts of the store that a component needs.
|
||||
|
||||
- **State Management Best Practices:**
|
||||
- **Single Source of Truth:** Keep the application state in Mobx stores and avoid duplicating data.
|
||||
- **Normalization:** Normalize data to reduce redundancy and improve data consistency.
|
||||
- **Immutability (with Mutation):** While Mobx encourages mutation, treat observable state as immutable from the perspective of components (i.e., components shouldn't directly mutate the store).
|
||||
|
||||
- **Error Handling Patterns:**
|
||||
- Implement centralized error handling using a dedicated error store.
|
||||
- Use try-catch blocks within actions to handle potential errors.
|
||||
- Display user-friendly error messages to the user.
|
||||
|
||||
## 4. Performance Considerations
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **`React.memo`:** Wrap components with `React.memo` to prevent unnecessary re-renders when props haven't changed.
|
||||
- **`useMemo` and `useCallback`:** Use `useMemo` and `useCallback` hooks to memoize values and callbacks, preventing unnecessary re-renders of child components.
|
||||
- **Computed Properties:** Use `computed` properties to derive data from observable state and cache the results.
|
||||
- **Optimize List Rendering:** Use `key` props when rendering lists and consider using virtualized lists for large datasets.
|
||||
|
||||
- **Memory Management:**
|
||||
- **Dispose of Observers:** Dispose of observers when components unmount to prevent memory leaks.
|
||||
- **Avoid Retaining Large Data Sets:** Remove or release references to large data sets when they are no longer needed.
|
||||
|
||||
- **Rendering Optimization:**
|
||||
- **Minimize Re-renders:** Optimize component rendering by using `React.memo` and avoiding unnecessary state updates.
|
||||
- **Use ShouldComponentUpdate (if needed):** In class components, use `shouldComponentUpdate` lifecycle method to control when a component should re-render. This is less common with `observer`. Be careful, can lead to bugs.
|
||||
|
||||
- **Bundle Size Optimization:**
|
||||
- **Code Splitting:** Implement code splitting to reduce the initial bundle size.
|
||||
- **Tree Shaking:** Use a bundler that supports tree shaking to remove unused code.
|
||||
- **Minification:** Minify your code to reduce the bundle size.
|
||||
|
||||
- **Lazy Loading Strategies:**
|
||||
- **React.lazy and Suspense:** Use React's built-in lazy loading mechanism.
|
||||
- **Dynamic Imports:** Use dynamic imports to load modules on demand.
|
||||
|
||||
## 5. Security Best Practices
|
||||
|
||||
- **Common Vulnerabilities:**
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user inputs to prevent XSS attacks.
|
||||
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection mechanisms.
|
||||
- **Injection Attacks:** Validate user inputs to prevent SQL injection and other injection attacks.
|
||||
|
||||
- **Input Validation:**
|
||||
- **Server-Side Validation:** Always validate user inputs on the server-side.
|
||||
- **Client-Side Validation:** Implement client-side validation to provide immediate feedback to the user.
|
||||
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- **JSON Web Tokens (JWT):** Use JWTs for authentication and authorization.
|
||||
- **Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of the application.
|
||||
|
||||
- **Data Protection Strategies:**
|
||||
- **Encryption:** Encrypt sensitive data both in transit and at rest.
|
||||
- **Data Masking:** Mask sensitive data to protect user privacy.
|
||||
|
||||
- **Secure API Communication:**
|
||||
- **HTTPS:** Use HTTPS for all API communication.
|
||||
- **Rate Limiting:** Implement rate limiting to prevent abuse.
|
||||
|
||||
## 6. Testing Approaches
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Test individual components and stores in isolation.
|
||||
- Mock dependencies to isolate the unit under test.
|
||||
- Use testing libraries like Jest and React Testing Library.
|
||||
|
||||
- **Integration Testing:**
|
||||
- Test the interaction between different components and stores.
|
||||
- Use a testing environment that closely resembles the production environment.
|
||||
|
||||
- **End-to-End Testing:**
|
||||
- Test the entire application flow from the user's perspective.
|
||||
- Use testing frameworks like Cypress or Selenium.
|
||||
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories for unit, integration, and end-to-end tests.
|
||||
- Use descriptive test names.
|
||||
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking libraries to mock dependencies in unit tests.
|
||||
- Use stubbing to replace complex dependencies with simpler implementations.
|
||||
|
||||
## 7. Common Pitfalls and Gotchas
|
||||
|
||||
- **Frequent Mistakes:**
|
||||
- Forgetting to decorate components with `observer`.
|
||||
- Modifying state outside of actions.
|
||||
- Not disposing of observers properly.
|
||||
- Over-observing state.
|
||||
|
||||
- **Edge Cases:**
|
||||
- Handling large datasets efficiently.
|
||||
- Dealing with complex asynchronous operations.
|
||||
- Managing nested observable objects.
|
||||
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of breaking changes in Mobx and React versions.
|
||||
- Consult the Mobx and React documentation for migration guides.
|
||||
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure compatibility with different browsers and devices.
|
||||
- Test your application on different platforms.
|
||||
|
||||
- **Debugging Strategies:**
|
||||
- Use the Mobx devtools to inspect observable state and track changes.
|
||||
- Use browser developer tools to debug React components.
|
||||
- Add logging statements to track the flow of data and execution.
|
||||
|
||||
## 8. Tooling and Environment
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **VS Code:** A popular code editor with excellent support for React and Mobx.
|
||||
- **Mobx Devtools:** A browser extension for inspecting Mobx state.
|
||||
- **React Devtools:** A browser extension for inspecting React components.
|
||||
|
||||
- **Build Configuration:**
|
||||
- **Webpack:** A popular module bundler for React applications.
|
||||
- **Parcel:** A zero-configuration bundler that's easy to use.
|
||||
- **Rollup:** A bundler focused on creating libraries and smaller bundles.
|
||||
|
||||
- **Linting and Formatting:**
|
||||
- **ESLint:** A JavaScript linter for enforcing code style and preventing errors.
|
||||
- **Prettier:** A code formatter for automatically formatting code.
|
||||
- **Husky/lint-staged:** Tools to automatically lint code before commits
|
||||
|
||||
- **Deployment Best Practices:**
|
||||
- **Continuous Integration/Continuous Deployment (CI/CD):** Automate the build, test, and deployment process.
|
||||
- **Caching:** Use caching to improve performance.
|
||||
- **Content Delivery Network (CDN):** Use a CDN to serve static assets.
|
||||
|
||||
- **CI/CD Integration:**
|
||||
- Integrate your application with a CI/CD pipeline to automate the build, test, and deployment process.
|
||||
- Use tools like Jenkins, Travis CI, or CircleCI.
|
||||
@@ -0,0 +1,196 @@
|
||||
---
|
||||
description: This rule provides comprehensive guidelines for React Native development, covering code organization, performance, security, testing, and common pitfalls. Adhering to these practices ensures maintainable, scalable, and efficient React Native applications.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
# React Native Best Practices
|
||||
|
||||
This document outlines best practices for developing React Native applications, covering various aspects from code organization to performance optimization.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
* **Directory Structure:**
|
||||
* Adopt a scalable and maintainable directory structure. Feature-based organization is often preferred.
|
||||
* Example:
|
||||
|
||||
src/
|
||||
├── components/ # Reusable UI components
|
||||
├── screens/ # App screens/views
|
||||
├── navigation/ # Navigation configurations
|
||||
├── services/ # API services and data fetching
|
||||
├── utils/ # Utility functions
|
||||
├── constants/ # Constant values
|
||||
├── context/ # React Context providers
|
||||
├── types/ # TypeScript type definitions
|
||||
└── App.tsx # Root component
|
||||
|
||||
* **File Naming Conventions:**
|
||||
* Use descriptive and consistent file names.
|
||||
* Components: `ComponentName.tsx` (or `.jsx`)
|
||||
* Styles: `ComponentName.styles.ts` (or `.js`)
|
||||
* Utility functions: `utilityName.ts` (or `.js`)
|
||||
* Consider using kebab-case for folders.
|
||||
* **Module Organization:**
|
||||
* Group related components, styles, and assets within the same directory.
|
||||
* Use `index.ts` (or `.js`) files to export modules, simplifying imports.
|
||||
* Example:
|
||||
|
||||
// components/Button/index.ts
|
||||
export { default as Button } from './Button';
|
||||
|
||||
* **Component Architecture:**
|
||||
* Favor functional components with hooks over class components.
|
||||
* Separate concerns using container and presentational components.
|
||||
* **Container components:** Handle data fetching and state management.
|
||||
* **Presentational components:** Focus on rendering UI based on props.
|
||||
* Use composition to create flexible and reusable components.
|
||||
* **Code Splitting Strategies:**
|
||||
* Implement lazy loading for screens and components to reduce initial bundle size.
|
||||
* Use `React.lazy` and `Suspense` for code splitting.
|
||||
* Dynamic imports can be useful for loading non-critical modules on demand.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
* **Design Patterns:**
|
||||
* **Higher-Order Components (HOCs):** Wrap components with shared logic.
|
||||
* **Render Props:** Share code between React components using a prop whose value is a function.
|
||||
* **Hooks:** Extract stateful logic into reusable functions.
|
||||
* **Compound Components:** Allow components to implicitly share state (e.g., Tabs).
|
||||
* **Recommended Approaches:**
|
||||
* **State Management:** Use appropriate state management solutions (e.g., Redux, Zustand, React Context) based on the application's complexity. For local state management, `useState` and `useReducer` hooks are preferred.
|
||||
* **API Calls:** Use `async/await` for asynchronous operations and handle errors gracefully.
|
||||
* **Navigation:** Utilize `react-navigation` or `react-native-navigation` for screen transitions and navigation logic.
|
||||
* **Anti-patterns:**
|
||||
* **Mutating state directly:** Use `setState` or state update functions from hooks.
|
||||
* **Passing too many props:** Refactor components or use context to share data.
|
||||
* **Overusing global state:** Consider component-level state when appropriate.
|
||||
* **Long functions:** Break down functions into smaller, more manageable pieces.
|
||||
* **State Management Best Practices:**
|
||||
* Choose the right state management tool for the job (Context API, Redux, Zustand, Recoil).
|
||||
* Keep state minimal and derive values when possible.
|
||||
* Use immutable data structures to simplify state updates.
|
||||
* Optimize re-renders by using `React.memo`, `useMemo`, and `useCallback`.
|
||||
* **Error Handling Patterns:**
|
||||
* Use `try/catch` blocks to handle synchronous errors.
|
||||
* Implement error boundaries to catch errors in React components.
|
||||
* Log errors to a monitoring service for tracking and analysis (e.g., Sentry, Bugsnag).
|
||||
* Provide user-friendly error messages and recovery options.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
* **Optimization Techniques:**
|
||||
* **Memoization:** Use `React.memo` to prevent unnecessary re-renders of components.
|
||||
* **PureComponent:** Use `PureComponent` for class components to perform shallow prop comparisons.
|
||||
* **Virtualization:** Use `FlatList` or `SectionList` for rendering large lists of data efficiently.
|
||||
* **Debouncing and Throttling:** Limit the rate at which functions are executed in response to rapid events (e.g., scrolling, typing).
|
||||
* **Memory Management:**
|
||||
* Avoid memory leaks by properly cleaning up event listeners and timers in `useEffect` hooks.
|
||||
* Release resources when components unmount.
|
||||
* Be mindful of image sizes and optimize them for mobile devices.
|
||||
* **Rendering Optimization:**
|
||||
* Minimize the number of re-renders by using `useCallback` and `useMemo` to memoize functions and values.
|
||||
* Avoid inline function definitions in render methods.
|
||||
* Use `shouldComponentUpdate` (for class components) or `React.memo` to prevent unnecessary renders.
|
||||
* **Bundle Size Optimization:**
|
||||
* Use code splitting to reduce the initial bundle size.
|
||||
* Remove unused code using tree shaking.
|
||||
* Optimize image assets using tools like ImageOptim or TinyPNG.
|
||||
* Analyze bundle size using tools like `webpack-bundle-analyzer`.
|
||||
* **Lazy Loading Strategies:**
|
||||
* Implement lazy loading for images using libraries like `react-native-fast-image`.
|
||||
* Lazy load components using `React.lazy` and `Suspense`.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
* **Common Vulnerabilities:**
|
||||
* **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input before rendering it in the UI.
|
||||
* **SQL Injection:** Use parameterized queries or ORMs to prevent SQL injection attacks.
|
||||
* **Insecure Data Storage:** Avoid storing sensitive data in plain text on the device.
|
||||
* **Man-in-the-Middle (MITM) Attacks:** Use HTTPS to encrypt communication between the app and the server.
|
||||
* **Input Validation:**
|
||||
* Validate all user input on both the client and server sides.
|
||||
* Use regular expressions to enforce input formats.
|
||||
* Sanitize input to remove potentially malicious characters.
|
||||
* **Authentication and Authorization Patterns:**
|
||||
* Use secure authentication methods like OAuth 2.0 or JWT.
|
||||
* Implement role-based access control to restrict access to sensitive data and functionality.
|
||||
* Store authentication tokens securely using the device's keychain or secure storage.
|
||||
* **Data Protection Strategies:**
|
||||
* Encrypt sensitive data at rest using encryption libraries.
|
||||
* Use secure storage options provided by the platform (e.g., Keychain on iOS, KeyStore on Android).
|
||||
* Avoid logging sensitive data.
|
||||
* **Secure API Communication:**
|
||||
* Use HTTPS for all API communication.
|
||||
* Implement proper authentication and authorization for API endpoints.
|
||||
* Protect against CSRF attacks by using anti-CSRF tokens.
|
||||
* Rate limit API requests to prevent abuse.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
* **Unit Testing:**
|
||||
* Test individual components and functions in isolation.
|
||||
* Use testing frameworks like Jest or Mocha.
|
||||
* Write tests for edge cases and error conditions.
|
||||
* **Integration Testing:**
|
||||
* Test the interaction between different components and modules.
|
||||
* Verify that data flows correctly between different parts of the application.
|
||||
* **End-to-End Testing:**
|
||||
* Test the entire application flow from start to finish.
|
||||
* Use testing frameworks like Detox or Appium.
|
||||
* Run tests on real devices or emulators.
|
||||
* **Test Organization:**
|
||||
* Organize tests in a way that mirrors the application's directory structure.
|
||||
* Use descriptive test names to clearly indicate what is being tested.
|
||||
* Keep tests small and focused.
|
||||
* **Mocking and Stubbing:**
|
||||
* Use mocking libraries like Jest's `jest.mock` to isolate components during testing.
|
||||
* Stub out dependencies to control their behavior.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
* **Frequent Mistakes:**
|
||||
* **Incorrectly using `setState`:** Understand the asynchronous nature of `setState` and use functional updates when necessary.
|
||||
* **Not optimizing images:** Large images can significantly impact performance.
|
||||
* **Ignoring memory leaks:** Failing to clean up event listeners and timers can lead to memory leaks.
|
||||
* **Over-rendering:** Unnecessary re-renders can degrade performance.
|
||||
* **Edge Cases:**
|
||||
* **Handling different screen sizes and densities:** Use responsive design techniques to adapt to various screen sizes.
|
||||
* **Dealing with network latency:** Implement loading indicators and error handling for API requests.
|
||||
* **Handling different locales and languages:** Use internationalization (i18n) libraries to support multiple languages.
|
||||
* **Version-Specific Issues:**
|
||||
* Be aware of breaking changes in React Native updates.
|
||||
* Test your application on different versions of React Native to ensure compatibility.
|
||||
* Use `react-native-upgrade-helper` to help with upgrades.
|
||||
* **Compatibility Concerns:**
|
||||
* Test your application on different devices and operating systems.
|
||||
* Be aware of platform-specific APIs and features.
|
||||
* Use conditional rendering or platform-specific code when necessary.
|
||||
* **Debugging Strategies:**
|
||||
* Use the React Native debugger to inspect component state and props.
|
||||
* Use `console.log` statements to trace code execution.
|
||||
* Use error logging to capture and track errors.
|
||||
* Learn to use the Chrome Developer Tools for debugging JavaScript code.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
* **Recommended Development Tools:**
|
||||
* **VS Code:** A popular code editor with excellent React Native support.
|
||||
* **React Native Debugger:** A standalone debugger for React Native applications.
|
||||
* **Expo CLI:** A tool for creating, building, and deploying React Native applications.
|
||||
* **Android Studio/Xcode:** The official IDEs for Android and iOS development, respectively.
|
||||
* **Build Configuration:**
|
||||
* Use environment variables to configure different build environments (e.g., development, staging, production).
|
||||
* Optimize build settings for performance.
|
||||
* **Linting and Formatting:**
|
||||
* Use ESLint and Prettier to enforce code style and prevent errors.
|
||||
* Configure ESLint with React Native-specific rules.
|
||||
* Use a pre-commit hook to automatically format code before committing.
|
||||
* **Deployment Best Practices:**
|
||||
* Use code signing to ensure the integrity of your application.
|
||||
* Follow the platform-specific deployment guidelines (e.g., Google Play Store, Apple App Store).
|
||||
* Use a continuous integration/continuous deployment (CI/CD) pipeline to automate the deployment process.
|
||||
* **CI/CD Integration:**
|
||||
* Use CI/CD tools like Jenkins, CircleCI, or GitHub Actions to automate building, testing, and deploying your application.
|
||||
* Configure CI/CD to run unit tests, integration tests, and end-to-end tests.
|
||||
* Automate the process of creating and deploying release builds.
|
||||
|
||||
By following these best practices, you can develop robust, scalable, and maintainable React Native applications.
|
||||
@@ -0,0 +1,267 @@
|
||||
---
|
||||
description: This rule enforces best practices for using react-query in React applications, covering code organization, performance, security, and testing.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
# react-query Best Practices
|
||||
|
||||
This document outlines the best practices for using react-query in React applications, covering various aspects such as code organization, performance considerations, security, and testing.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure Best Practices
|
||||
|
||||
* **Feature-based Organization:** Group react-query hooks and related components within feature-specific directories. This improves modularity and maintainability.
|
||||
|
||||
src/
|
||||
├── features/
|
||||
│ ├── users/
|
||||
│ │ ├── components/
|
||||
│ │ │ ├── UserList.tsx
|
||||
│ │ │ └── UserDetails.tsx
|
||||
│ │ ├── hooks/
|
||||
│ │ │ ├── useUsersQuery.ts
|
||||
│ │ │ └── useCreateUserMutation.ts
|
||||
│ │ ├── api/
|
||||
│ │ │ └── usersApi.ts
|
||||
│ │ └── types/
|
||||
│ │ └── user.ts
|
||||
│ ├── products/
|
||||
│ └── ...
|
||||
├── ...
|
||||
|
||||
|
||||
* **Dedicated API Service Layer:** Abstract API interaction logic into separate modules. This allows for easier testing and decoupling of components from specific API implementations. Consider using a dedicated `api` directory within each feature.
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
* **Consistent Naming:** Follow a consistent naming convention for react-query hooks. Prefix hooks with `use` and postfix with `Query` or `Mutation` to clearly indicate their purpose (e.g., `usePostsQuery`, `useUpdatePostMutation`).
|
||||
|
||||
* **Descriptive Names:** Use descriptive names for files and variables to improve code readability. For example, `useFetchUsersQuery.ts` is more informative than `useUsers.ts`.
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
* **Custom Hooks for Reusability:** Encapsulate react-query logic within custom hooks to promote reusability and separation of concerns.
|
||||
|
||||
typescript
|
||||
// src/features/users/hooks/useUsersQuery.ts
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { fetchUsers } from '../api/usersApi';
|
||||
|
||||
export const useUsersQuery = () => {
|
||||
return useQuery('users', fetchUsers);
|
||||
};
|
||||
|
||||
|
||||
* **Separate Query and Mutation Files:** Organize queries and mutations into separate files or modules. This enhances code readability and maintainability.
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
* **Presentational and Container Components:** Separate presentational components (UI) from container components (data fetching and state management). This improves testability and reusability.
|
||||
|
||||
* **Composition:** Use component composition to build complex UIs from smaller, reusable components. Leverage React Context for shared state when appropriate.
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
* **Route-Based Splitting:** Split your application into separate bundles based on routes. This reduces the initial load time and improves perceived performance. React.lazy and React.Suspense can assist with this.
|
||||
|
||||
* **Component-Based Splitting:** Split large components into smaller chunks that can be loaded on demand. This can improve the performance of individual pages or components.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to react-query
|
||||
|
||||
* **Custom Hooks for Data Fetching:** As highlighted earlier, encapsulating react-query logic within custom hooks. This promotes reusability and separation of concerns. These hooks will typically return the result of a `useQuery` or `useMutation` call.
|
||||
|
||||
* **Optimistic Updates:** Implement optimistic updates to improve perceived performance. This involves updating the UI before the API request completes, and then reverting the changes if the request fails. react-query provides utilities like `onMutate` to handle this.
|
||||
|
||||
* **Pessimistic Updates:** Update the UI only after a successful response from the API. Simpler to implement but provides a less snappy user experience.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
* **Prefetching Data:** Prefetch data for routes or components that the user is likely to visit next. This can significantly improve the user experience. Use `queryClient.prefetchQuery`.
|
||||
|
||||
* **Pagination and Infinite Scrolling:** Implement pagination and infinite scrolling to handle large datasets efficiently. react-query provides hooks like `useInfiniteQuery` to simplify this.
|
||||
|
||||
* **Dependent Queries:** Fetch data based on the result of a previous query. Use the `enabled` option in `useQuery` to conditionally execute queries.
|
||||
|
||||
typescript
|
||||
const { data: user } = useQuery(['user', userId], () => fetchUser(userId));
|
||||
|
||||
const { data: posts } = useQuery(['posts', user?.id], () => fetchPosts(user.id), {
|
||||
enabled: !!user,
|
||||
});
|
||||
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* **Directly Calling API in Components:** Avoid making API calls directly within components. This makes testing difficult and tightly couples components to specific API implementations.
|
||||
|
||||
* **Ignoring Error Handling:** Always handle errors properly. Display user-friendly error messages and provide options for retrying requests.
|
||||
|
||||
* **Over-fetching Data:** Fetch only the data that is required by the component. Use GraphQL or API query parameters to reduce the amount of data transferred.
|
||||
|
||||
* **Deeply Nested Queries:** Avoid deeply nesting queries, as this can lead to performance issues and make the code difficult to understand. Consider combining queries or using a different approach.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
* **Local vs. Global State:** Determine whether data should be stored in local component state or in a global state management solution. Use local state for component-specific data and global state for data that needs to be shared across multiple components.
|
||||
|
||||
* **react-query as a State Manager:** Leverage react-query's built-in caching and state management capabilities. Avoid using external state management libraries for data that is already managed by react-query.
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
* **Centralized Error Handling:** Implement centralized error handling to provide consistent error messages and logging.
|
||||
|
||||
* **Retry Logic:** Implement retry logic to automatically retry failed requests. react-query provides options for configuring retry behavior.
|
||||
|
||||
* **Error Boundaries:** Use Error Boundaries to catch errors that occur during rendering. This prevents the entire application from crashing.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
* **Query Invalidation:** Invalidate queries when data changes. This ensures that the UI is always up-to-date.
|
||||
|
||||
* **Stale-While-Revalidate:** Use the `staleTime` and `cacheTime` options to configure how long data should be considered fresh. `staleWhileRevalidate` allows the UI to display cached data while fetching fresh data in the background.
|
||||
|
||||
* **Window Focus Refetching:** Configure refetching on window focus to keep data fresh when the user switches back to the application.
|
||||
|
||||
* **Polling/Refetch Intervals:** Use `refetchInterval` to periodically refetch data. This is useful for data that changes frequently.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
* **Query Cache Management:** Understand how react-query manages its cache. Configure the `cacheTime` option to control how long data is stored in the cache.
|
||||
|
||||
* **Garbage Collection:** Ensure that unused queries are garbage collected properly. Use the `gcTime` option to configure how long inactive queries should be kept in the cache.
|
||||
|
||||
### 3.3 Rendering Optimization
|
||||
|
||||
* **Memoization:** Use `React.memo` to prevent unnecessary re-renders of components. This is especially important for components that display data fetched from react-query.
|
||||
|
||||
* **Virtualization:** Use virtualization techniques (e.g., `react-window`, `react-virtualized`) to efficiently render large lists of data.
|
||||
|
||||
### 3.4 Bundle Size Optimization
|
||||
|
||||
* **Tree Shaking:** Ensure that your build process is configured for tree shaking. This removes unused code from the final bundle.
|
||||
|
||||
* **Code Splitting:** As mentioned earlier, use code splitting to reduce the initial load time.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
* **Lazy Load Components:** Use `React.lazy` to lazy load components that are not immediately needed.
|
||||
|
||||
* **Lazy Load Data:** Fetch data only when it is needed. Use dependent queries to fetch data based on user interactions.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. Use a library like DOMPurify to sanitize HTML.
|
||||
|
||||
* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection to prevent attackers from performing actions on behalf of the user. Use a library or framework that provides CSRF protection.
|
||||
|
||||
* **Injection Attacks:** Protect against injection attacks by validating user input and using parameterized queries.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
* **Client-Side Validation:** Implement client-side validation to provide immediate feedback to the user.
|
||||
|
||||
* **Server-Side Validation:** Always validate user input on the server-side to prevent malicious data from being stored in the database.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
* **JSON Web Tokens (JWT):** Use JWTs for authentication. Store the JWT in a secure cookie or in local storage (with caution). Use `httpOnly` flag on cookies containing JWTs when possible to prevent client-side script access.
|
||||
|
||||
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of the application. Use middleware or custom hooks to check user roles.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data at rest and in transit. Use HTTPS to encrypt data in transit. Encrypt sensitive data in the database.
|
||||
|
||||
* **Data Masking:** Mask sensitive data in logs and reports. This prevents sensitive data from being exposed to unauthorized users.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
* **HTTPS:** Use HTTPS for all API communication. This encrypts data in transit and prevents eavesdropping.
|
||||
|
||||
* **API Rate Limiting:** Implement API rate limiting to prevent abuse.
|
||||
|
||||
* **CORS:** Configure CORS properly to prevent cross-origin requests from unauthorized domains.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
* **Test Custom Hooks:** Unit test custom react-query hooks to ensure they are working correctly. Mock the API calls using libraries like `msw` (Mock Service Worker).
|
||||
|
||||
* **Test Components in Isolation:** Unit test components in isolation to ensure they render correctly and handle user interactions properly. Use libraries like `react-testing-library`.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
* **Test Data Flow:** Integration test the data flow between components and APIs. Verify that data is fetched correctly and displayed properly.
|
||||
|
||||
* **Test Error Handling:** Integration test error handling scenarios to ensure that errors are handled properly.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
* **Simulate User Interactions:** Use end-to-end testing frameworks like Cypress or Playwright to simulate user interactions and verify that the application is working correctly from the user's perspective.
|
||||
|
||||
* **Test Critical Paths:** Focus on testing critical user flows, such as login, registration, and checkout.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
* **Colocate Tests with Components:** Colocate tests with the components they are testing. This makes it easier to find and maintain tests.
|
||||
|
||||
* **Use Descriptive Test Names:** Use descriptive test names to clearly indicate what each test is verifying.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
* **Mock API Calls:** Use mocking libraries like `msw` to mock API calls during testing. This allows you to test components in isolation without relying on a real API.
|
||||
|
||||
* **Stub External Dependencies:** Stub external dependencies to isolate components and make tests more predictable.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
* **Forgetting to Invalidate Queries:** Failing to invalidate queries when data changes can lead to stale data being displayed in the UI.
|
||||
|
||||
* **Incorrect Cache Configuration:** Incorrectly configuring the `cacheTime` and `staleTime` options can lead to performance issues or stale data.
|
||||
|
||||
* **Not Handling Errors Properly:** Not handling errors properly can lead to unexpected behavior and a poor user experience.
|
||||
|
||||
* **Over-relying on Default Configuration:** Customizing react-query to match specific needs is essential.
|
||||
|
||||
* **Ignoring Devtools:** The react-query devtools are invaluable for debugging and understanding what is happening under the hood.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
* **VS Code:** Use VS Code with extensions like ESLint, Prettier, and TypeScript to improve developer productivity.
|
||||
|
||||
* **React Developer Tools:** Use the React Developer Tools browser extension to inspect React components and state.
|
||||
|
||||
* **react-query Devtools:** Use the react-query Devtools to inspect the react-query cache and track query and mutation status.
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
* **Webpack or Parcel:** Use a bundler like Webpack or Parcel to bundle your code for production. Configure the bundler for tree shaking and code splitting.
|
||||
|
||||
* **Babel:** Use Babel to transpile your code to older versions of JavaScript. This ensures that your code is compatible with older browsers.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
* **ESLint:** Use ESLint to enforce coding standards and prevent errors. Configure ESLint to use a popular style guide like Airbnb or Google.
|
||||
|
||||
* **Prettier:** Use Prettier to automatically format your code. This ensures that your code is consistently formatted and easy to read.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
* **CDN:** Use a CDN to serve static assets. This improves performance and reduces the load on your server.
|
||||
|
||||
* **Caching:** Configure caching properly on your server and CDN. This reduces the number of requests to your server and improves performance.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
* **Automated Testing:** Integrate automated testing into your CI/CD pipeline. This ensures that your code is tested automatically before it is deployed.
|
||||
|
||||
* **Automated Deployment:** Automate the deployment process to reduce the risk of errors and improve efficiency.
|
||||
@@ -0,0 +1,283 @@
|
||||
---
|
||||
description: Enforces best practices for structuring and maintaining React-Redux applications, focusing on code organization, performance, and maintainability. This rule provides guidelines for developers to write efficient, scalable, and testable React-Redux code.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
# React-Redux Best Practices
|
||||
|
||||
This document outlines best practices for developing React applications with Redux for state management. Following these guidelines will help you write maintainable, scalable, and performant code.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1. Directory Structure
|
||||
|
||||
Organize your code around features rather than technical concerns. A feature-based directory structure promotes modularity and makes it easier to understand the application's purpose.
|
||||
|
||||
|
||||
src/
|
||||
├── app/
|
||||
│ ├── components/
|
||||
│ │ └── App.tsx
|
||||
│ └── App.css
|
||||
├── features/
|
||||
│ ├── featureName/
|
||||
│ │ ├── components/
|
||||
│ │ │ ├── FeatureComponent.tsx
|
||||
│ │ │ └── FeatureComponent.css
|
||||
│ │ ├── FeatureSlice.ts # Redux slice for the feature
|
||||
│ │ ├── FeatureSelectors.ts # Selectors for accessing feature state
|
||||
│ │ ├── FeatureActions.ts # Actions related to this feature
|
||||
│ │ └── api.ts # API calls related to the feature
|
||||
│ ├── anotherFeature/
|
||||
│ │ └── ...
|
||||
├── store.ts # Redux store configuration
|
||||
├── index.tsx # Entry point for the React application
|
||||
└── ...
|
||||
|
||||
|
||||
### 1.2. File Naming Conventions
|
||||
|
||||
* **Components:** Use PascalCase (e.g., `MyComponent.tsx`).
|
||||
* **Redux Slice Files:** Use PascalCase and end with `Slice.ts` or `Slice.js` (e.g., `UserSlice.ts`).
|
||||
* **Selectors:** `selectors.ts` or `selectors.js` or `FeatureSelectors.ts` to include a feature name prefix
|
||||
* **Actions:** `actions.ts` or `actions.js` or `FeatureActions.ts` to include a feature name prefix
|
||||
* **Styles:** Use either `ComponentName.module.css` (for CSS Modules) or `ComponentName.css` (for global styles).
|
||||
* **Utility Functions:** Use camelCase (e.g., `formatDate.ts`).
|
||||
|
||||
### 1.3. Module Organization
|
||||
|
||||
* **Encapsulation:** Each feature should be a self-contained module with its components, actions, reducers, and selectors.
|
||||
* **Single Responsibility Principle:** Each module should have a single, well-defined purpose.
|
||||
* **Clear Boundaries:** Define clear boundaries between modules to minimize dependencies and prevent tight coupling.
|
||||
|
||||
### 1.4. Component Architecture
|
||||
|
||||
* **Presentational and Container Components:**
|
||||
* **Presentational (Dumb) Components:** Focus on rendering UI and receiving data and callbacks as props. They should be reusable and independent of Redux.
|
||||
* **Container (Smart) Components:** Connect to the Redux store and pass data and actions to presentational components. Use `connect` or `useSelector` and `useDispatch` hooks.
|
||||
* **Small and Reusable Components:** Break down complex UIs into smaller, reusable components to promote code reuse and maintainability.
|
||||
* **Component Composition:** Build complex UIs by composing smaller components.
|
||||
|
||||
### 1.5. Code Splitting Strategies
|
||||
|
||||
* **Route-Based Splitting:** Split the application into chunks based on routes to reduce the initial load time. Use `React.lazy` and `Suspense` for lazy loading components.
|
||||
* **Component-Based Splitting:** Split large components into smaller chunks that can be loaded on demand. Use dynamic imports for loading components asynchronously.
|
||||
* **Library Splitting:** Extract commonly used libraries into separate chunks to allow browsers to cache them independently.
|
||||
|
||||
## 2. Common Patterns and Anti-Patterns
|
||||
|
||||
### 2.1. Design Patterns
|
||||
|
||||
* **Selectors:** Use selectors to abstract the state shape and compute derived data. Selectors improve performance by memoizing results and prevent components from re-rendering unnecessarily.
|
||||
* **Custom Hooks:** Create custom hooks for accessing Redux state and dispatching actions. This simplifies component logic and promotes code reuse. For example:
|
||||
|
||||
typescript
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import { increment, decrement } from './counterSlice';
|
||||
import { RootState } from './store';
|
||||
|
||||
export const useCounter = () => {
|
||||
const count = useSelector((state: RootState) => state.counter.value);
|
||||
const dispatch = useDispatch();
|
||||
|
||||
const handleIncrement = () => {
|
||||
dispatch(increment());
|
||||
};
|
||||
|
||||
const handleDecrement = () => {
|
||||
dispatch(decrement());
|
||||
};
|
||||
|
||||
return { count, handleIncrement, handleDecrement };
|
||||
};
|
||||
|
||||
* **Redux Toolkit:** Utilize Redux Toolkit to simplify Redux setup and reduce boilerplate code. Redux Toolkit provides utilities for creating reducers, actions, and the store.
|
||||
|
||||
### 2.2. Recommended Approaches
|
||||
|
||||
* **Normalize State:** Structure your state as a normalized data structure, where each piece of data has a unique ID, and relationships between data are represented by IDs. This improves performance and simplifies data management. Use libraries like Normalizr to help with this.
|
||||
* **Immutability:** Treat your state as immutable and use immutable update patterns. This ensures predictable state transitions and prevents unexpected side effects.
|
||||
* **Middleware for Side Effects:** Use Redux middleware (e.g., Redux Thunk, Redux Saga) to handle asynchronous operations and side effects. Avoid performing side effects directly in reducers.
|
||||
|
||||
### 2.3. Anti-Patterns and Code Smells
|
||||
|
||||
* **Mutating State Directly:** Never mutate the state directly in reducers. Always create a new copy of the state with the desired changes.
|
||||
* **Performing Side Effects in Reducers:** Reducers should be pure functions and should not perform any side effects (e.g., API calls, logging).
|
||||
* **Storing UI State in Redux:** Avoid storing UI-specific state (e.g., component visibility, form input values) in the Redux store. Store UI state locally in component state.
|
||||
* **Over-reliance on Global State:** Avoid putting everything in the Redux store. Only store data that needs to be accessed by multiple components or across the entire application. Consider React Context or local component state for component-specific data.
|
||||
|
||||
### 2.4. State Management Best Practices
|
||||
|
||||
* **Minimize Global State:** Only store data in the Redux store that needs to be shared across multiple components. For component-specific state, use local component state.
|
||||
* **Use Selectors:** Use selectors to access and transform data from the Redux store. This allows you to abstract the state shape and prevent components from re-rendering unnecessarily.
|
||||
* **Immutable Updates:** Always update state immutably to ensure predictable state transitions and prevent unexpected side effects. Use libraries like Immer to simplify immutable updates.
|
||||
|
||||
### 2.5. Error Handling Patterns
|
||||
|
||||
* **Centralized Error Handling:** Implement a centralized error handling mechanism to catch and handle errors consistently throughout the application. Use error boundary components to catch errors in the UI.
|
||||
* **Action Creators for Errors:** Dispatch error actions to the Redux store when errors occur. This allows you to track errors and display error messages in the UI.
|
||||
* **Logging Errors:** Log errors to a central logging service for debugging and monitoring purposes.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1. Optimization Techniques
|
||||
|
||||
* **Memoization:** Use memoization techniques (e.g., `React.memo`, `useMemo`, Reselect) to prevent components from re-rendering unnecessarily.
|
||||
* **Batch Updates:** Batch multiple Redux dispatches into a single update to improve performance. Use `redux-batched-updates` or `unstable_batchedUpdates` from React DOM.
|
||||
* **Virtualization:** Use virtualization techniques (e.g., `react-window`, `react-virtualized`) to efficiently render large lists and tables.
|
||||
* **Code Splitting:** Split the application into smaller chunks to reduce the initial load time.
|
||||
|
||||
### 3.2. Memory Management
|
||||
|
||||
* **Avoid Memory Leaks:** Be mindful of memory leaks, especially in event listeners, timers, and subscriptions. Clean up resources properly when components unmount.
|
||||
* **Use WeakRefs:** Use WeakRefs to hold references to objects without preventing them from being garbage collected.
|
||||
* **Profile Memory Usage:** Use the browser's developer tools to profile memory usage and identify potential memory leaks.
|
||||
|
||||
### 3.3. Rendering Optimization
|
||||
|
||||
* **ShouldComponentUpdate / React.memo:** Use `shouldComponentUpdate` (for class components) or `React.memo` (for functional components) to prevent components from re-rendering unnecessarily.
|
||||
* **Pure Components:** Use pure components to automatically implement `shouldComponentUpdate` based on prop comparisons.
|
||||
* **Immutable Data Structures:** Use immutable data structures to make it easier to detect changes and prevent re-renders.
|
||||
|
||||
### 3.4. Bundle Size Optimization
|
||||
|
||||
* **Tree Shaking:** Use tree shaking to remove dead code from your bundles. Configure your bundler (e.g., Webpack, Parcel) to enable tree shaking.
|
||||
* **Code Splitting:** Split the application into smaller chunks to reduce the initial load time.
|
||||
* **Minification:** Minify your code to reduce the bundle size.
|
||||
* **Compression:** Compress your bundles using gzip or Brotli.
|
||||
|
||||
### 3.5. Lazy Loading Strategies
|
||||
|
||||
* **Route-Based Lazy Loading:** Load components only when their corresponding routes are visited.
|
||||
* **Component-Based Lazy Loading:** Load components on demand when they become visible in the UI.
|
||||
* **Image Lazy Loading:** Load images only when they scroll into view.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1. Common Vulnerabilities and Prevention
|
||||
|
||||
* **Cross-Site Scripting (XSS):** Prevent XSS vulnerabilities by sanitizing user input and escaping output.
|
||||
* **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using anti-CSRF tokens.
|
||||
* **Injection Attacks:** Prevent injection attacks (e.g., SQL injection, command injection) by validating user input and using parameterized queries.
|
||||
* **Authentication and Authorization:** Implement secure authentication and authorization mechanisms to protect sensitive data and resources.
|
||||
|
||||
### 4.2. Input Validation
|
||||
|
||||
* **Server-Side Validation:** Always validate user input on the server-side to prevent malicious data from being stored in the database.
|
||||
* **Client-Side Validation:** Use client-side validation to provide immediate feedback to users and reduce the load on the server.
|
||||
* **Whitelisting:** Use whitelisting to allow only specific characters or patterns in user input.
|
||||
|
||||
### 4.3. Authentication and Authorization Patterns
|
||||
|
||||
* **JSON Web Tokens (JWT):** Use JWTs for authentication and authorization. JWTs are stateless and can be easily verified on the server-side.
|
||||
* **OAuth 2.0:** Use OAuth 2.0 for delegated authorization. OAuth 2.0 allows users to grant third-party applications access to their resources without sharing their credentials.
|
||||
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
|
||||
|
||||
### 4.4. Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
* **Data Masking:** Mask sensitive data to prevent unauthorized access.
|
||||
* **Data Anonymization:** Anonymize data to remove personally identifiable information (PII).
|
||||
|
||||
### 4.5. Secure API Communication
|
||||
|
||||
* **HTTPS:** Use HTTPS to encrypt communication between the client and the server.
|
||||
* **API Keys:** Use API keys to authenticate API requests.
|
||||
* **Rate Limiting:** Implement rate limiting to prevent abuse and denial-of-service attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1. Unit Testing Strategies
|
||||
|
||||
* **Test Reducers:** Test reducers to ensure that they handle actions correctly and update the state as expected.
|
||||
* **Test Selectors:** Test selectors to ensure that they return the correct data from the state.
|
||||
* **Test Actions:** Test action creators to ensure that they return the correct actions.
|
||||
* **Test Components:** Test components to ensure that they render correctly and handle user interactions as expected. Use tools like React Testing Library.
|
||||
|
||||
### 5.2. Integration Testing
|
||||
|
||||
* **Test Component Interactions:** Test how components interact with each other and with the Redux store.
|
||||
* **Test Data Flow:** Test the flow of data through the application, from the UI to the Redux store and back.
|
||||
* **Test API Integrations:** Test how the application integrates with external APIs.
|
||||
|
||||
### 5.3. End-to-End Testing
|
||||
|
||||
* **Test User Flows:** Test complete user flows to ensure that the application functions correctly from end to end. Use tools like Cypress or Playwright.
|
||||
* **Test Critical Functionality:** Test critical functionality (e.g., login, checkout) to ensure that it is working as expected.
|
||||
* **Test Accessibility:** Test the application for accessibility to ensure that it is usable by people with disabilities.
|
||||
|
||||
### 5.4. Test Organization
|
||||
|
||||
* **Test Folder Structure:** Organize tests in a way that mirrors the application's directory structure.
|
||||
* **Test Suites:** Group tests into logical suites based on functionality or component.
|
||||
* **Test Naming Conventions:** Use clear and consistent naming conventions for tests.
|
||||
|
||||
### 5.5. Mocking and Stubbing
|
||||
|
||||
* **Mock API Calls:** Mock API calls to isolate components and reducers during testing.
|
||||
* **Stub External Dependencies:** Stub external dependencies to control their behavior during testing.
|
||||
* **Use Mock Store:** Use a mock Redux store to test components that are connected to the store.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1. Frequent Mistakes
|
||||
|
||||
* **Forgetting to Connect Components:** Forgetting to connect components to the Redux store, resulting in components not receiving state updates.
|
||||
* **Incorrectly Mapping State to Props:** Incorrectly mapping state to props, resulting in components not receiving the correct data.
|
||||
* **Not Updating State Immutably:** Not updating state immutably, leading to unexpected side effects and re-renders.
|
||||
* **Using `setState` with Redux:** Mixing `setState` with Redux can lead to inconsistencies and difficult-to-debug issues. Avoid using `setState` in components connected to Redux, unless for purely local, non-Redux-related state.
|
||||
|
||||
### 6.2. Edge Cases
|
||||
|
||||
* **Race Conditions:** Be aware of race conditions when handling asynchronous operations.
|
||||
* **Memory Leaks:** Watch out for memory leaks in event listeners, timers, and subscriptions.
|
||||
* **Performance Bottlenecks:** Identify and address performance bottlenecks, such as unnecessary re-renders or slow API calls.
|
||||
|
||||
### 6.3. Version-Specific Issues
|
||||
|
||||
* **Breaking Changes:** Be aware of breaking changes when upgrading React and Redux.
|
||||
* **Deprecated Features:** Avoid using deprecated features and migrate to the recommended alternatives.
|
||||
|
||||
### 6.4. Compatibility Concerns
|
||||
|
||||
* **Browser Compatibility:** Test the application in different browsers to ensure compatibility.
|
||||
* **Device Compatibility:** Test the application on different devices to ensure compatibility.
|
||||
|
||||
### 6.5. Debugging Strategies
|
||||
|
||||
* **Redux DevTools:** Use the Redux DevTools to inspect the Redux store, track actions, and time travel through state changes.
|
||||
* **Console Logging:** Use console logging to debug code and track the flow of data.
|
||||
* **Breakpoints:** Use breakpoints to pause execution and inspect variables in the debugger.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1. Recommended Development Tools
|
||||
|
||||
* **Redux DevTools:** The Redux DevTools extension for Chrome and Firefox allows you to inspect the Redux store, track actions, and time travel through state changes.
|
||||
* **React Developer Tools:** The React Developer Tools extension for Chrome and Firefox allows you to inspect the React component tree and profile component performance.
|
||||
* **ESLint:** ESLint is a linter that helps you identify and fix code style issues and potential errors.
|
||||
* **Prettier:** Prettier is a code formatter that automatically formats your code to ensure consistency.
|
||||
|
||||
### 7.2. Build Configuration
|
||||
|
||||
* **Webpack:** Webpack is a module bundler that bundles your code and dependencies into optimized bundles for production.
|
||||
* **Parcel:** Parcel is a zero-configuration bundler that is easy to use and provides fast build times.
|
||||
* **Create React App:** Create React App is a tool that sets up a React development environment with sensible defaults.
|
||||
|
||||
### 7.3. Linting and Formatting
|
||||
|
||||
* **ESLint:** Use ESLint to enforce code style rules and prevent potential errors. Configure ESLint to use a popular style guide, such as Airbnb or Standard.
|
||||
* **Prettier:** Use Prettier to automatically format your code to ensure consistency. Integrate Prettier with ESLint to automatically fix code style issues.
|
||||
* **Husky and Lint-Staged:** Use Husky and Lint-Staged to automatically run linters and formatters on staged files before committing code.
|
||||
|
||||
### 7.4. Deployment Best Practices
|
||||
|
||||
* **Environment Variables:** Use environment variables to configure the application for different environments (e.g., development, staging, production).
|
||||
* **Continuous Integration:** Use a continuous integration (CI) system to automatically build and test the application whenever code is committed.
|
||||
* **Continuous Deployment:** Use a continuous deployment (CD) system to automatically deploy the application to production whenever a new release is created.
|
||||
* **Caching:** Configure caching on the server-side and client-side to improve performance.
|
||||
|
||||
### 7.5. CI/CD Integration
|
||||
|
||||
* **GitHub Actions:** Use GitHub Actions to automate the build, test, and deployment process.
|
||||
* **CircleCI:** Use CircleCI to automate the build, test, and deployment process.
|
||||
* **Jenkins:** Use Jenkins to automate the build, test, and deployment process.
|
||||
@@ -0,0 +1,167 @@
|
||||
---
|
||||
description: Enforces best practices for React development, covering code structure, performance, security, and testing to ensure maintainable and efficient applications.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
- **Use Functional Components with Hooks:**
|
||||
- Favor functional components over class components for simplicity and better performance.
|
||||
- Leverage React Hooks (useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, useImperativeHandle, useLayoutEffect, useDebugValue) for managing state, side effects, and context.
|
||||
|
||||
- **Component Composition:**
|
||||
- Build complex UIs by composing smaller, reusable components.
|
||||
- Use props to pass data down the component tree and callbacks to handle events.
|
||||
|
||||
- **Meaningful Component Names:**
|
||||
- Give component names that accurately reflect their functionality.
|
||||
- Follow a consistent naming convention (e.g., PascalCase for components, camelCase for props).
|
||||
|
||||
- **Keep Components Small and Focused:**
|
||||
- Adhere to the Single Responsibility Principle; each component should have a clear, focused purpose.
|
||||
- Break down large components into smaller, more manageable pieces.
|
||||
|
||||
- **Destructuring Props:**
|
||||
- Use destructuring to access props within functional components for improved readability.
|
||||
|
||||
- **Avoid Inline Styles:**
|
||||
- Use CSS modules, styled-components, or a CSS-in-JS library for managing styles instead of inline styles.
|
||||
- Keep styles separate from component logic for better maintainability.
|
||||
|
||||
- **Use Arrow Functions:**
|
||||
- Use arrow functions for concise syntax and lexical `this` binding.
|
||||
- Be mindful of performance implications when passing arrow functions directly as props; consider using `useCallback`.
|
||||
|
||||
- **PropTypes for Type Checking (with alternatives):**
|
||||
- Use PropTypes (though consider TypeScript) to define the expected types of props passed to components.
|
||||
- Enforce type checking at runtime to catch type-related errors early.
|
||||
- Strongly consider TypeScript for static type checking for enhanced code quality and maintainability.
|
||||
|
||||
- **Immutability:**
|
||||
- Treat state as immutable; avoid directly modifying state objects.
|
||||
- Use `setState`, the spread operator (`...`), or immutable data structures (e.g., Immutable.js) to update state.
|
||||
|
||||
- **Code Organization and Structure:**
|
||||
- **Directory Structure:**
|
||||
- Organize components into folders based on features or modules.
|
||||
- Use a `components` directory for reusable UI elements.
|
||||
- Consider a `hooks` directory for custom hooks.
|
||||
- Separate API services into a `services` or `api` directory.
|
||||
- **File Naming Conventions:**
|
||||
- Use `.jsx` or `.tsx` extensions for React components.
|
||||
- Name files according to the component they export (e.g., `MyComponent.jsx`).
|
||||
- Use `index.js` or `index.ts` files to export multiple components from a directory.
|
||||
- **Module Organization:**
|
||||
- Use ES modules (`import` and `export`) for modular code.
|
||||
- Group related components and logic into modules.
|
||||
- **Component Architecture:**
|
||||
- **Atomic Design:** Consider using Atomic Design principles (Atoms, Molecules, Organisms, Templates, Pages) to structure your components.
|
||||
- **Presentational and Container Components:** Separate presentational (UI-focused) and container (logic-focused) components.
|
||||
- **Code Splitting:**
|
||||
- Use React.lazy and Suspense to lazy-load components and reduce initial bundle size.
|
||||
- Implement route-based code splitting for larger applications.
|
||||
- Consider using dynamic imports for splitting non-route components as well.
|
||||
|
||||
- **Common Patterns and Anti-patterns:**
|
||||
- **Design Patterns:**
|
||||
- **Higher-Order Components (HOCs):** Use HOCs to share logic between components.
|
||||
- **Render Props:** Use render props for more flexible code reuse.
|
||||
- **Compound Components:** Create components that implicitly share state and behavior with their children (e.g., `<Tabs>`, `<Tab>`).
|
||||
- **Provider Pattern:** Use the Context API to provide data to a subtree of components.
|
||||
- **Recommended Approaches:**
|
||||
- Use controlled components for forms to manage input values in React state.
|
||||
- Use keys when rendering lists of elements for efficient updates.
|
||||
- Use memoization techniques (React.memo, useMemo, useCallback) to prevent unnecessary re-renders.
|
||||
- **Anti-patterns:**
|
||||
- **Direct DOM Manipulation:** Avoid directly manipulating the DOM; use React's virtual DOM instead.
|
||||
- **Mutating State Directly:** Never directly modify state; use `setState` or the appropriate hook update function.
|
||||
- **Over-reliance on Global State:** Avoid storing too much state in global stores; consider component-level state or context when appropriate.
|
||||
- **State Management:**
|
||||
- **Component State:** Use `useState` for simple component-level state.
|
||||
- **Context API:** Use the Context API for sharing state across a subtree of components.
|
||||
- **Redux/Zustand/Recoil/MobX:** Consider using a state management library (Redux, Zustand, Recoil, MobX) for complex application state.
|
||||
- **Error Handling:**
|
||||
- **Error Boundaries:** Use Error Boundaries to catch errors during rendering and prevent the entire application from crashing.
|
||||
- **Try/Catch Blocks:** Use try/catch blocks for handling errors in event handlers and lifecycle methods.
|
||||
|
||||
- **Performance Considerations:**
|
||||
- **Memoization:**
|
||||
- Use `React.memo` to memoize functional components and prevent unnecessary re-renders.
|
||||
- Use `useMemo` to memoize computed values and prevent unnecessary recalculations.
|
||||
- Use `useCallback` to memoize event handler functions and prevent unnecessary re-renders of child components.
|
||||
- **Virtualization:**
|
||||
- Use virtualization libraries (e.g., `react-window`, `react-virtualized`) for rendering large lists of data efficiently.
|
||||
- **Debouncing and Throttling:**
|
||||
- Use debouncing and throttling techniques to limit the frequency of function calls in response to user input.
|
||||
- **Image Optimization:**
|
||||
- Optimize images for the web to reduce file sizes and improve loading times.
|
||||
- Use lazy loading for images that are not immediately visible.
|
||||
- **Bundle Size Optimization:**
|
||||
- Use code splitting to reduce the initial bundle size.
|
||||
- Remove unused code with tree shaking.
|
||||
- Compress code with minification.
|
||||
- **Rendering Optimization:**
|
||||
- Use `shouldComponentUpdate` (in class components) or `React.memo` (in functional components) to prevent unnecessary re-renders.
|
||||
- Implement pure components (components that only re-render when their props change) for performance gains.
|
||||
- **Lazy Loading:**
|
||||
- Use `React.lazy` and `Suspense` to load components on demand and improve initial load time.
|
||||
|
||||
- **Security Best Practices:**
|
||||
- **XSS Prevention:**
|
||||
- Sanitize user input to prevent cross-site scripting (XSS) attacks.
|
||||
- Use React's built-in escaping mechanisms to render data safely.
|
||||
- **CSRF Protection:**
|
||||
- Implement cross-site request forgery (CSRF) protection to prevent unauthorized requests.
|
||||
- Use anti-CSRF tokens to verify requests.
|
||||
- **Authentication and Authorization:**
|
||||
- Use secure authentication and authorization patterns to protect sensitive data and functionality.
|
||||
- Implement strong password policies.
|
||||
- Use multi-factor authentication.
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS to secure communication between the client and server.
|
||||
- **Secure API Communication:**
|
||||
- Validate API responses to prevent unexpected data from compromising the application.
|
||||
|
||||
- **Testing Approaches:**
|
||||
- **Unit Testing:**
|
||||
- Write unit tests to verify the behavior of individual components and functions.
|
||||
- Use testing libraries like Jest and React Testing Library.
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to verify the interaction between multiple components and modules.
|
||||
- **End-to-End Testing:**
|
||||
- Write end-to-end tests to verify the entire application flow.
|
||||
- Use testing frameworks like Cypress or Playwright.
|
||||
- **Test Organization:**
|
||||
- Organize tests into a `__tests__` directory alongside the component files.
|
||||
- Follow a consistent naming convention for test files (e.g., `MyComponent.test.jsx`).
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing techniques to isolate components during testing.
|
||||
- Mock external dependencies like API calls and browser APIs.
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- **Incorrect `this` Binding:**
|
||||
- Be mindful of `this` binding in class components; use arrow functions or `bind` to ensure the correct context.
|
||||
- **Missing Keys in Lists:**
|
||||
- Provide unique keys to elements when rendering lists to prevent rendering issues.
|
||||
- **Asynchronous State Updates:**
|
||||
- Understand how `setState` and hook update functions handle asynchronous updates; use functional updates when necessary.
|
||||
- **Memory Leaks:**
|
||||
- Clean up side effects in `useEffect` hooks to prevent memory leaks.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of compatibility concerns when upgrading React versions.
|
||||
- Consult the React documentation and release notes for migration guides.
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- **Recommended Development Tools:**
|
||||
- VS Code with React-specific extensions (e.g., ESLint, Prettier, Babel).
|
||||
- Chrome DevTools for debugging.
|
||||
- React Developer Tools extension for inspecting component hierarchy and state.
|
||||
- **Build Configuration:**
|
||||
- Use tools like webpack, Parcel, or Rollup for bundling and optimizing code.
|
||||
- Configure Babel to transpile JSX and modern JavaScript syntax.
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint with React-specific rules to enforce code style and best practices.
|
||||
- Use Prettier to automatically format code.
|
||||
- **Deployment Best Practices:**
|
||||
- Use a CDN to serve static assets.
|
||||
- Use server-side rendering (SSR) or static site generation (SSG) for improved performance and SEO.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate CI/CD pipelines for automated testing, building, and deployment.
|
||||
@@ -0,0 +1,322 @@
|
||||
---
|
||||
description: This comprehensive guide outlines best practices for SolidJS development, covering code organization, performance, security, testing, and common pitfalls. It provides actionable guidelines for building maintainable, efficient, and secure SolidJS applications.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
# SolidJS Best Practices: A Comprehensive Guide
|
||||
|
||||
This document provides a detailed overview of best practices for SolidJS development, covering various aspects from code organization to security and performance. It aims to guide developers in building robust, scalable, and maintainable SolidJS applications.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure Best Practices
|
||||
|
||||
A well-defined directory structure is crucial for maintaining a large SolidJS application. Here's a recommended structure:
|
||||
|
||||
|
||||
my-solid-app/
|
||||
├── src/
|
||||
│ ├── components/
|
||||
│ │ ├── Button/
|
||||
│ │ │ ├── Button.tsx
|
||||
│ │ │ ├── Button.module.css
|
||||
│ │ │ ├── Button.test.tsx
|
||||
│ │ ├── Card/
|
||||
│ │ │ ├── Card.tsx
|
||||
│ │ │ ├── Card.module.css
|
||||
│ │ ├── index.ts # Exports all components
|
||||
│ ├── contexts/
|
||||
│ │ ├── ThemeContext.tsx
|
||||
│ ├── hooks/
|
||||
│ │ ├── useTheme.ts
|
||||
│ ├── utils/
|
||||
│ │ ├── api.ts
|
||||
│ │ ├── helpers.ts
|
||||
│ ├── routes/
|
||||
│ │ ├── Home.tsx
|
||||
│ │ ├── About.tsx
|
||||
│ ├── styles/
|
||||
│ │ ├── global.css
|
||||
│ ├── App.tsx
|
||||
│ ├── index.tsx
|
||||
│ ├── types.d.ts # Global type definitions
|
||||
│ ├── vite-env.d.ts # vite type definitions
|
||||
├── public/
|
||||
│ ├── favicon.svg
|
||||
│ ├── assets/
|
||||
├── .env
|
||||
├── vite.config.ts
|
||||
├── tsconfig.json
|
||||
├── package.json
|
||||
├── README.md
|
||||
|
||||
|
||||
**Explanation:**
|
||||
|
||||
* **src/:** Contains the source code of your application.
|
||||
* **components/:** Reusable UI components. Each component should have its own directory containing the component file, styles, and tests.
|
||||
* **contexts/:** SolidJS Context providers for managing global state and shared data.
|
||||
* **hooks/:** Custom hooks for reusable logic.
|
||||
* **utils/:** Utility functions such as API calls, data formatting, etc.
|
||||
* **routes/:** Components that define different routes in your application.
|
||||
* **styles/:** Global styles or shared CSS modules.
|
||||
* **App.tsx:** The root component of your application.
|
||||
* **index.tsx:** Entry point for rendering the App component into the DOM.
|
||||
* **types.d.ts:** Global typescript type definitions for the project
|
||||
* **vite-env.d.ts:** vite environment type definitions
|
||||
* **public/:** Static assets such as images, fonts, etc.
|
||||
* **.env:** Stores environment variables.
|
||||
* **vite.config.ts:** Vite configuration file.
|
||||
* **tsconfig.json:** TypeScript configuration file.
|
||||
* **package.json:** Node.js package file.
|
||||
* **README.md:** Project documentation.
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
* **Components:** Use PascalCase for component file names (e.g., `Button.tsx`, `UserProfile.jsx`).
|
||||
* **Hooks:** Use camelCase prefixed with `use` for hook file names (e.g., `useTheme.ts`, `useFetchData.js`).
|
||||
* **Utilities:** Use camelCase for utility file names (e.g., `api.ts`, `formatDate.js`).
|
||||
* **Styles:** Use the `.module.css` extension for CSS modules (e.g., `Button.module.css`). If using other styling solutions like styled-components, follow their recommended practices.
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
* **Keep components modular:** Each component should have a single responsibility.
|
||||
* **Export components:** Export components to make them reusable in other parts of the application (e.g., `export default Button;`).
|
||||
* **Create an `index.ts` file:** In each directory (e.g., `components/`) export all the modules in that directory. This allows simpler imports from other components. e.g., `import {Button, Card} from '../components'`
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
* **Functional Components:** Use functional components with Solid's reactivity system for managing state and UI updates. Avoid class components.
|
||||
* **Props:** Use props to pass data from parent to child components. Be explicit about prop types using TypeScript.
|
||||
* **Context API:** Use Solid's Context API for sharing data between components without prop drilling. Use cases: themes, user authentication, global configuration.
|
||||
* **Signals:** Employ SolidJS Signals for managing component-level state. Prefer derived signals or memoization for expensive computations.
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
* **Route-Based Splitting:** Use dynamic imports to load components only when a route is visited. Leverage Solid Router's lazy loading capabilities with `lazy`.
|
||||
* **Component-Based Splitting:** Split large components into smaller chunks that can be loaded on demand. Use `Suspense` to handle loading states.
|
||||
* **Library Splitting:** If using large libraries, consider splitting them into smaller chunks or using tree-shaking to remove unused code.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to SolidJS
|
||||
|
||||
* **Renderless Components:** Create components that encapsulate logic without rendering any UI elements. They can be used as hooks or utility functions to share logic between components.
|
||||
* **Compound Components:** Build components that work together implicitly, often using Context to share state. (e.g., Tabs, Accordions).
|
||||
* **Reactivity-Based Composition:** Compose components based on shared reactive state, rather than inheritance. This allows more flexibility and better performance.
|
||||
* **Custom Control Flow Components:** Create reusable components to handle conditional rendering or list iteration with specific optimization strategies. Examples include more performant alternatives to `<For/>` in certain specific use cases.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
* **Fetching Data:** Use `createResource` for handling asynchronous data fetching. Use `AbortController` for cancelling requests on component unmount or data changes.
|
||||
* **Managing Forms:** Use signals to track form input values. Implement validation logic and handle form submission.
|
||||
* **Handling Events:** Attach event handlers to elements using JSX attributes (e.g., `onClick`). Use arrow functions or bind methods to ensure correct `this` context.
|
||||
* **Global State Management:** Use Solid's Context API or a dedicated state management library (e.g., `solid-zustand`, `solid-js/store`) for sharing data between components.
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* **Reading and Writing to the Same Signal in an Effect:** This creates an infinite loop. Use the functional update form `setCount(count => count + 1)` or derived signals.
|
||||
* **Writing to Signals in Effects for Derived Values:** Prefer derived signals or memoization for expensive computations (using `createMemo`).
|
||||
* **Destructuring Props:** This breaks reactivity. Access props directly or use `mergeProps` and `splitProps`.
|
||||
* **Using `.map` and Ternary Operators for Control Flow:** Use Solid's control flow components (`<For>`, `<Index>`, `<Show>`) to avoid unnecessary DOM elements.
|
||||
* **Mutating Resource Data Directly:** Always create new objects when mutating resource data to prevent unnecessary re-renders. use `createMutable` judiciously only where mutability is needed.
|
||||
* **Ignoring Cleanup Functions:** Neglecting `onCleanup` can lead to memory leaks and unexpected behavior when components unmount.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
* **Component-Level State:** Use signals for managing simple, component-specific state.
|
||||
* **Context API:** For sharing data between components without prop drilling, especially themes or user authentication.
|
||||
* **Global Stores:** Use store solutions or third-party libraries (e.g., `solid-zustand`, `solid-js/store`) for complex global state management.
|
||||
* **Immutability:** Treat state as immutable. Always create new objects/arrays when updating state, especially with resources or stores.
|
||||
* **Single Source of Truth:** Ensure that each piece of state has a single, authoritative source. Avoid duplicating state across components.
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
* **`Suspense` for Loading States:** Wrap asynchronous operations like `createResource` with `Suspense` to display loading indicators.
|
||||
* **Error Boundaries:** Implement error boundaries to catch errors during rendering and display fallback UI.
|
||||
* **Try-Catch Blocks:** Use `try-catch` blocks for handling synchronous errors or errors in event handlers.
|
||||
* **Centralized Error Logging:** Implement a centralized error logging mechanism to track and monitor errors in your application.
|
||||
* **User-Friendly Error Messages:** Display user-friendly error messages to guide users on how to resolve issues.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
* **Fine-Grained Reactivity:** Solid's fine-grained reactivity ensures that only the necessary parts of the UI are updated when state changes. Leverage this by breaking down components into smaller, more focused units.
|
||||
* **Derived Signals and Memos:** Use derived signals and memos to avoid recomputing expensive values unnecessarily.
|
||||
* **Control Flow Components:** Use `<For>`, `<Index>`, and `<Show>` for efficient conditional rendering and list iteration.
|
||||
* **Lazy Loading:** Load components and modules only when they are needed.
|
||||
* **Virtualization:** For rendering large lists, use virtualization techniques to only render the visible items.
|
||||
* **Debouncing and Throttling:** Implement debouncing or throttling for event handlers that trigger frequent updates.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
* **Cleanup Functions:** Always use `onCleanup` to release resources when a component is unmounted, such as timers, event listeners, and subscriptions.
|
||||
* **Avoid Memory Leaks:** Be mindful of potential memory leaks when using closures or retaining references to DOM elements.
|
||||
* **Weak References:** Use `WeakRef` or `WeakMap` for holding references to objects without preventing them from being garbage collected.
|
||||
|
||||
### 3.3 Rendering Optimization
|
||||
|
||||
* **Minimize DOM Updates:** Solid's reactivity system minimizes DOM updates, but avoid unnecessary renders by optimizing component structure and state management.
|
||||
* **Batch Updates:** Use `batchedUpdates` to batch multiple state updates into a single render cycle (use with caution).
|
||||
* **Avoid Inline Styles:** Prefer CSS classes or CSS modules for styling components.
|
||||
* **Use CSS Transitions and Animations:** Leverage CSS transitions and animations for smoother UI updates.
|
||||
|
||||
### 3.4 Bundle Size Optimization
|
||||
|
||||
* **Tree Shaking:** Use tree shaking to remove unused code from your bundle. Vite automatically performs tree shaking.
|
||||
* **Code Splitting:** Split your application into smaller chunks that can be loaded on demand.
|
||||
* **Minification and Compression:** Minify and compress your code to reduce bundle size. Vite handles minification by default.
|
||||
* **Image Optimization:** Optimize images by compressing them and using appropriate formats (e.g., WebP).
|
||||
* **Dependency Analysis:** Analyze your dependencies to identify and remove unnecessary libraries.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
* **Route-Based Lazy Loading:** Load components only when a route is visited using dynamic imports and the `lazy` function from Solid Router.
|
||||
* **Component-Based Lazy Loading:** Split large components into smaller chunks that can be loaded on demand.
|
||||
* **Conditional Lazy Loading:** Load components based on specific conditions, such as user interactions or device capabilities.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user inputs and escaping data when rendering it in the DOM. Avoid using `dangerouslySetInnerHTML`.
|
||||
* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection by using anti-CSRF tokens in forms and validating them on the server.
|
||||
* **SQL Injection:** Prevent SQL injection attacks by using parameterized queries or ORMs when interacting with databases.
|
||||
* **Authentication and Authorization:** Secure your application by implementing proper authentication and authorization mechanisms.
|
||||
* **Denial-of-Service (DoS):** Protect against DoS attacks by implementing rate limiting, input validation, and resource quotas.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
* **Server-Side Validation:** Always validate user inputs on the server to prevent malicious data from being stored in your database.
|
||||
* **Client-Side Validation:** Provide client-side validation for a better user experience, but never rely on it as the sole means of protection.
|
||||
* **Sanitize Inputs:** Sanitize user inputs to remove potentially harmful characters or code.
|
||||
* **Use Validation Libraries:** Use validation libraries to simplify the input validation process.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
* **JSON Web Tokens (JWT):** Use JWTs for managing user authentication and authorization.
|
||||
* **OAuth 2.0:** Implement OAuth 2.0 for third-party authentication and authorization.
|
||||
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
|
||||
* **Multi-Factor Authentication (MFA):** Implement MFA for enhanced security.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data at rest and in transit using appropriate encryption algorithms.
|
||||
* **Data Masking:** Mask sensitive data when displaying it to users or storing it in logs.
|
||||
* **Data Redaction:** Redact sensitive data from logs and audit trails.
|
||||
* **Data Retention Policies:** Implement data retention policies to ensure that data is only stored for as long as it is needed.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
* **HTTPS:** Use HTTPS for all API communication to encrypt data in transit.
|
||||
* **API Keys:** Use API keys for authenticating clients and controlling access to your APIs.
|
||||
* **Rate Limiting:** Implement rate limiting to prevent abuse of your APIs.
|
||||
* **Input Validation:** Validate all API inputs to prevent malicious data from being processed.
|
||||
* **Output Encoding:** Encode API outputs to prevent XSS attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
* **Test Individual Components:** Unit tests should focus on testing individual components in isolation.
|
||||
* **Mock Dependencies:** Mock dependencies to isolate the component being tested.
|
||||
* **Test All Scenarios:** Test all possible scenarios and edge cases.
|
||||
* **Use Assertions:** Use assertions to verify that the component behaves as expected.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
* **Test Component Interactions:** Integration tests should focus on testing the interactions between components.
|
||||
* **Mock External Services:** Mock external services to isolate the component being tested.
|
||||
* **Test Data Flow:** Test the flow of data between components.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
* **Test the Entire Application:** End-to-end tests should focus on testing the entire application from the user's perspective.
|
||||
* **Use a Testing Framework:** Use a testing framework such as Cypress or Playwright to automate the testing process.
|
||||
* **Test User Flows:** Test common user flows to ensure that the application works as expected.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
* **Colocate Tests:** Place test files alongside the components they are testing.
|
||||
* **Use a Consistent Naming Convention:** Use a consistent naming convention for test files (e.g., `Button.test.tsx`).
|
||||
* **Organize Tests by Feature:** Organize tests by feature or module.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
* **Use Mocking Libraries:** Use mocking libraries such as Jest or Vitest to create mocks and stubs.
|
||||
* **Mock External Dependencies:** Mock external dependencies to isolate the component being tested.
|
||||
* **Stub API Calls:** Stub API calls to control the data returned by the API.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
|
||||
* **Incorrectly Using Effects:** Misunderstanding the dependency tracking of `createEffect` can lead to unnecessary re-runs or infinite loops.
|
||||
* **Forgetting `onCleanup`:** Not using `onCleanup` for resources and subscriptions causes memory leaks.
|
||||
* **Mutating State Directly:** Directly mutating objects or arrays used as state leads to unexpected behavior and broken reactivity.
|
||||
* **Over-Optimizing Prematurely:** Focusing on micro-optimizations before addressing fundamental architectural issues.
|
||||
* **Not Understanding Solid's Reactivity:** Failing to grasp the nuances of Solid's reactive system can lead to inefficient code.
|
||||
|
||||
### 6.2 Edge Cases to Be Aware Of
|
||||
|
||||
* **SSR Hydration Issues:** When doing SSR, ensure that the initial state on the server matches the client to avoid hydration errors.
|
||||
* **Reactivity with Non-Reactive Values:** Passing plain JS objects or arrays to components without making them reactive can cause issues with updates.
|
||||
* **Transitions and Resource Updates:** Interactions between transitions and resource updates can sometimes be tricky, especially around loading states.
|
||||
* **Nested Reactivity:** Managing reactivity in complex, deeply nested data structures can be challenging.
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
|
||||
* **Compatibility:** Consider backwards compatibility when upgrading SolidJS or related libraries.
|
||||
* **Deprecations:** Be aware of deprecated features and APIs and migrate to the recommended alternatives.
|
||||
* **Bug Fixes:** Stay up-to-date with bug fixes and security patches in newer versions of SolidJS.
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
|
||||
* **Browser Compatibility:** Test your application in different browsers to ensure compatibility.
|
||||
* **Device Compatibility:** Test your application on different devices, such as desktops, tablets, and mobile phones.
|
||||
* **Accessibility:** Ensure that your application is accessible to users with disabilities.
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
|
||||
* **Use Browser Developer Tools:** Use the browser's developer tools to inspect the DOM, network requests, and console output.
|
||||
* **SolidJS Devtools:** Use the SolidJS Devtools extension to inspect components, signals, and resources.
|
||||
* **Logging:** Add logging statements to your code to track the flow of execution and the values of variables.
|
||||
* **Debugging Tools:** Use debugging tools such as VS Code's debugger to step through your code and inspect variables.
|
||||
* **Reproducible Examples:** Create reproducible examples to isolate and debug issues more effectively.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
* **Vite:** Use Vite as the build tool. SolidJS uses Vite as its default.
|
||||
* **VS Code:** Use VS Code as the code editor, along with extensions for TypeScript, ESLint, and Prettier.
|
||||
* **SolidJS Devtools:** Use the SolidJS Devtools browser extension to inspect components, signals, and resources.
|
||||
* **TypeScript:** Utilize TypeScript for type safety and improved code maintainability.
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
* **Vite Configuration:** Configure Vite to optimize your build for production (e.g., code splitting, minification, compression).
|
||||
* **TypeScript Configuration:** Configure TypeScript to enforce strict type checking and code quality.
|
||||
* **Environment Variables:** Use environment variables to store sensitive data and configure your application for different environments.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
* **ESLint:** Use ESLint to enforce code style and identify potential errors.
|
||||
* **Prettier:** Use Prettier to automatically format your code.
|
||||
* **Husky:** Use Husky to run linters and formatters before committing code.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
* **Choose a Hosting Platform:** Select a suitable hosting platform for your SolidJS application (e.g., Netlify, Vercel, AWS).
|
||||
* **Configure a Production Environment:** Configure your hosting platform to use a production environment with appropriate settings.
|
||||
* **Automate Deployment:** Automate the deployment process using CI/CD tools.
|
||||
* **Monitor Your Application:** Monitor your application for errors and performance issues.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
* **Choose a CI/CD Tool:** Select a CI/CD tool such as GitHub Actions, GitLab CI, or CircleCI.
|
||||
* **Configure CI/CD Pipelines:** Configure CI/CD pipelines to automatically build, test, and deploy your application.
|
||||
* **Automate Testing:** Automate unit tests, integration tests, and end-to-end tests in your CI/CD pipelines.
|
||||
* **Automate Deployment:** Automate the deployment process to deploy new versions of your application with minimal manual intervention.
|
||||
|
||||
This document provides a comprehensive set of best practices for SolidJS development. By following these guidelines, developers can build high-quality, maintainable, and secure SolidJS applications.
|
||||
@@ -0,0 +1,157 @@
|
||||
---
|
||||
description: Comprehensive Svelte best practices covering code structure, performance, security, testing, and common pitfalls. This rule provides guidance on writing maintainable, efficient, and secure Svelte applications.
|
||||
globs: **/*.svelte
|
||||
---
|
||||
- **Manipulate the DOM with HTML:** Utilize Svelte's HTML-centric approach to manipulate the DOM.
|
||||
- **Solve challenges with HTML/CSS first:** Prioritize solving problems with HTML and CSS before resorting to JavaScript.
|
||||
- **Write short components:** Aim for concise and focused components to improve readability and maintainability.
|
||||
- **Write concise reactive `$:` blocks:** Keep reactive statements short and easy to understand.
|
||||
- **Scope CSS to the actual component:** Ensure that CSS styles are scoped to the component to avoid conflicts.
|
||||
- **Avoid hard coding data or dimensions:** Use dynamic data and responsive design techniques instead of hard-coded values.
|
||||
- **Keep objects immutable:** Treat objects as immutable to prevent unexpected side effects and improve performance.
|
||||
- **Use two-way binding effectively:** Leverage two-way binding for efficient data synchronization but be mindful of its potential impact on performance for complex scenarios.
|
||||
|
||||
## 1. Code Organization and Structure:
|
||||
|
||||
- **Directory Structure Best Practices:**
|
||||
- `src/`: Contains all the application source code.
|
||||
- `src/components/`: Holds reusable Svelte components, categorized further by feature or domain (e.g., `src/components/Button/`, `src/components/Form/`).
|
||||
- `src/lib/`: Contains utility functions, helper modules, and reusable logic that is not specific to a component.
|
||||
- `src/routes/`: For SvelteKit applications, this directory defines the application's routes.
|
||||
- `src/stores/`: Stores for global state management (if using Svelte's stores).
|
||||
- `static/`: Static assets like images, fonts, and other resources.
|
||||
- **File Naming Conventions:**
|
||||
- Components: Use PascalCase (e.g., `MyComponent.svelte`).
|
||||
- Utility functions: Use camelCase (e.g., `formatDate.js`).
|
||||
- Stores: Use descriptive names related to the data they hold (e.g., `userStore.js`).
|
||||
- **Module Organization:**
|
||||
- Group related components and utilities into modules within their respective directories.
|
||||
- Use `index.js` or `index.svelte` files to export multiple components or functions from a directory, providing a cleaner import experience.
|
||||
- **Component Architecture:**
|
||||
- Favor a component-based architecture where UI is broken down into small, reusable components.
|
||||
- Consider using a composition pattern where complex components are built by composing simpler ones.
|
||||
- Separate concerns: Keep components focused on presentation logic and delegate data fetching or business logic to services or stores.
|
||||
- **Code Splitting Strategies:**
|
||||
- Use dynamic imports (`import()`) to load components or modules on demand, reducing the initial bundle size.
|
||||
- Leverage SvelteKit's built-in code splitting capabilities for route-based splitting.
|
||||
- Consider splitting large components into smaller, lazily loaded sub-components.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns:
|
||||
|
||||
- **Design Patterns Specific to Svelte:**
|
||||
- **Store pattern:** Use Svelte's stores for managing application state and reactivity.
|
||||
- **Action pattern:** Use Svelte's actions for manipulating DOM elements or integrating with third-party libraries.
|
||||
- **Component composition:** Build complex UIs by composing smaller, reusable components.
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- **Form handling:** Use Svelte's two-way binding (`bind:value`) for simple forms. For more complex scenarios, consider libraries like Formik or Svelte Formly.
|
||||
- **Data fetching:** Use `fetch` or libraries like Axios for fetching data from APIs. Handle loading and error states appropriately.
|
||||
- **Event handling:** Use Svelte's event directives (e.g., `on:click`) for handling DOM events.
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **Overusing global state:** Avoid putting everything in a global store. Use component-level state when appropriate.
|
||||
- **Directly manipulating the DOM outside of actions:** Rely on Svelte's reactivity system to update the DOM.
|
||||
- **Writing overly complex components:** Break down large components into smaller, more manageable ones.
|
||||
- **State Management Best Practices:**
|
||||
- Use Svelte's built-in stores for managing global or application-level state.
|
||||
- Consider using reactive declarations (`$:`) to derive state from other state variables.
|
||||
- Keep state updates predictable and avoid modifying state directly.
|
||||
- For complex state management needs, explore libraries like Redux or Zustand (though often unnecessary in Svelte).
|
||||
- **Error Handling Patterns:**
|
||||
- Use try-catch blocks to handle potential errors during data fetching or other asynchronous operations.
|
||||
- Display user-friendly error messages in the UI.
|
||||
- Log errors to the console or a logging service for debugging purposes.
|
||||
- Implement global error handling to catch unhandled exceptions.
|
||||
|
||||
## 3. Performance Considerations:
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Minimize DOM updates:** Svelte is very efficient at updating the DOM, but unnecessary updates can still impact performance. Use reactive declarations judiciously.
|
||||
- **Use `{#each}` blocks efficiently:** Key your `{#each}` blocks with unique identifiers to help Svelte efficiently update the list.
|
||||
- **Avoid unnecessary component re-renders:** Use the `$:` syntax effectively to only update components when necessary.
|
||||
- **Memory Management:**
|
||||
- Avoid memory leaks by properly cleaning up event listeners and subscriptions when components are destroyed (using `onDestroy`).
|
||||
- Be mindful of large data structures in stores, and consider using techniques like pagination or virtualization to manage them efficiently.
|
||||
- **Rendering Optimization:**
|
||||
- Use the `svelte:options` tag with the `immutable` option for components that receive immutable data as props.
|
||||
- Use `shouldUpdate` to prevent rendering for unchanged immutable props.
|
||||
- **Bundle Size Optimization:**
|
||||
- Use production builds with minification and tree shaking to remove unused code.
|
||||
- Use dynamic imports for code splitting.
|
||||
- Optimize images and other assets.
|
||||
- **Lazy Loading Strategies:**
|
||||
- Use dynamic imports to lazy load components or modules that are not immediately needed.
|
||||
- Implement lazy loading for images or other resources that are below the fold.
|
||||
|
||||
## 4. Security Best Practices:
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user input before displaying it in the UI. Svelte automatically escapes HTML entities, but be careful when using `@html` or `{@debug}`.
|
||||
- **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to protect against CSRF attacks.
|
||||
- **SQL Injection:** If interacting with a database, use parameterized queries to prevent SQL injection attacks.
|
||||
- **Input Validation:**
|
||||
- Validate user input on both the client-side and server-side.
|
||||
- Use appropriate data types and validation rules to prevent invalid data from being processed.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use secure authentication mechanisms like OAuth or JWT.
|
||||
- Implement proper authorization checks to ensure that users only have access to the resources they are allowed to access.
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure storage mechanisms for storing sensitive data.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API communication.
|
||||
- Validate API responses to ensure that they are valid and not malicious.
|
||||
|
||||
## 5. Testing Approaches:
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Use a testing framework like Jest or Mocha to write unit tests for individual components and utility functions.
|
||||
- Mock external dependencies to isolate the code being tested.
|
||||
- **Integration Testing:**
|
||||
- Use a testing framework like Cypress or Playwright to write integration tests that verify the interaction between different components or modules.
|
||||
- Test the integration with APIs and other external services.
|
||||
- **End-to-End Testing:**
|
||||
- Use a testing framework like Cypress or Playwright to write end-to-end tests that simulate user interactions with the application.
|
||||
- Test the entire application flow from start to finish.
|
||||
- **Test Organization:**
|
||||
- Organize tests into directories that mirror the application's directory structure.
|
||||
- Use descriptive names for test files and test cases.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking libraries like Jest's `jest.fn()` or Sinon.js to mock external dependencies.
|
||||
- Use stubbing to replace complex or slow dependencies with simpler implementations for testing purposes.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas:
|
||||
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- **Incorrect reactivity usage:** Failing to understand how Svelte's reactivity system works can lead to unexpected behavior.
|
||||
- **Over-reliance on `$: `:** Although reactive declarations are powerful, overusing them can make code harder to read and debug. Consider if a regular variable or function would be more appropriate.
|
||||
- **Mutating props directly:** Modifying props directly inside a component can lead to unexpected side effects.
|
||||
- **Edge Cases to Be Aware Of:**
|
||||
- **Transition and animation behavior:** Understanding how transitions and animations interact with component updates is important for creating smooth user experiences.
|
||||
- **Server-side rendering (SSR) considerations:** When using SvelteKit, be aware of the differences between client-side and server-side execution environments.
|
||||
- **Version-Specific Issues:**
|
||||
- Consult the Svelte changelog and migration guides when upgrading to a new version to avoid compatibility issues.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that your code is compatible with the target browsers and devices.
|
||||
- Use polyfills or transpilers to support older browsers if necessary.
|
||||
- **Debugging Strategies:**
|
||||
- Use the Svelte Devtools browser extension for inspecting component state and reactivity.
|
||||
- Use `console.log` or the `debugger` statement to debug code execution.
|
||||
- Use SvelteKit's built-in error handling and logging features.
|
||||
|
||||
## 7. Tooling and Environment:
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **VS Code with the Svelte extension:** Provides syntax highlighting, code completion, and other useful features.
|
||||
- **Svelte Devtools:** A browser extension for inspecting Svelte component state and reactivity.
|
||||
- **ESLint and Prettier:** For linting and formatting code.
|
||||
- **Build Configuration:**
|
||||
- Use a build tool like Vite or Rollup to bundle your Svelte code for production.
|
||||
- Configure the build tool to perform optimizations like minification and tree shaking.
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint with the `eslint-plugin-svelte3` plugin to lint your Svelte code.
|
||||
- Use Prettier with the `prettier-plugin-svelte` plugin to format your Svelte code.
|
||||
- **Deployment Best Practices:**
|
||||
- Deploy your Svelte application to a CDN or a serverless platform like Netlify or Vercel.
|
||||
- Configure your server to serve the application's static assets with proper caching headers.
|
||||
- **CI/CD Integration:**
|
||||
- Use a CI/CD platform like GitHub Actions or GitLab CI to automate the build, testing, and deployment process.
|
||||
- Run tests and linting checks on every commit to ensure code quality.
|
||||
@@ -0,0 +1,306 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices and coding standards for SvelteKit development, covering code structure, performance, security, testing, and common pitfalls. It aims to improve code quality, maintainability, and overall project health.
|
||||
globs: **/*.svelte
|
||||
---
|
||||
# SvelteKit Best Practices
|
||||
|
||||
This guide provides comprehensive best practices for developing SvelteKit applications. It covers various aspects, including code organization, performance considerations, security measures, and common pitfalls to avoid.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1. Directory Structure Best Practices
|
||||
|
||||
* **`src/lib`**: Reusable components, utilities, and stores. Organize by feature or domain.
|
||||
* **`src/routes`**: Defines the application's routes. Each directory represents a route segment.
|
||||
* **`src/routes/+page.svelte`**: Represents a page component for a route.
|
||||
* **`src/routes/+layout.svelte`**: Layout component that wraps the page. Useful for consistent UI elements.
|
||||
* **`src/routes/+page.server.ts`**: Server-side code for handling data fetching and form submissions for a page.
|
||||
* **`src/routes/+layout.server.ts`**: Server-side code for layout data, loaded before any +page.server.ts data.
|
||||
* **`src/hooks.server.ts`**: Handle server-side requests and responses. Useful for authentication and session management.
|
||||
* **`static`**: Static assets like images, fonts, and other files served directly.
|
||||
* **`tests`**: Directory for all tests, mirroring the source structure for clarity.
|
||||
|
||||
Example:
|
||||
|
||||
|
||||
src/
|
||||
├── lib/
|
||||
│ ├── components/
|
||||
│ │ ├── Button.svelte
|
||||
│ │ └── Card.svelte
|
||||
│ ├── utils/
|
||||
│ │ ├── api.ts
|
||||
│ │ └── helpers.ts
|
||||
│ └── stores/
|
||||
│ └── user.ts
|
||||
├── routes/
|
||||
│ ├── +
|
||||
│ │ └── page.svelte
|
||||
│ ├── about/
|
||||
│ │ ├── +
|
||||
│ │ │ └── page.svelte
|
||||
│ │ └── +page.server.ts
|
||||
│ └── blog/
|
||||
│ ├── [slug]/
|
||||
│ │ ├── +
|
||||
│ │ │ └── page.svelte
|
||||
│ │ └── +page.server.ts
|
||||
│ └── +
|
||||
│ └── page.svelte
|
||||
├── hooks.server.ts
|
||||
└── app.d.ts
|
||||
|
||||
|
||||
### 1.2. File Naming Conventions
|
||||
|
||||
* **Components**: PascalCase (e.g., `MyComponent.svelte`).
|
||||
* **Utility functions**: camelCase (e.g., `formatDate.ts`).
|
||||
* **Stores**: camelCase (e.g., `userStore.ts`).
|
||||
* **Route files**: Follow SvelteKit's routing conventions (`+page.svelte`, `+layout.svelte`, etc.).
|
||||
|
||||
### 1.3. Module Organization
|
||||
|
||||
* Group related functionality into modules.
|
||||
* Use `src/lib` for reusable modules.
|
||||
* Employ clear and descriptive module names.
|
||||
* Leverage SvelteKit's `$lib` alias for importing modules from `src/lib`.
|
||||
|
||||
### 1.4. Component Architecture
|
||||
|
||||
* **Atomic Design**: Break down UI into small, reusable components (atoms, molecules, organisms, templates, pages).
|
||||
* **Component Composition**: Compose complex UIs from simpler components.
|
||||
* **Props and Events**: Use props for data input and events for component output.
|
||||
* **Slots**: Allow parent components to inject content into child components.
|
||||
|
||||
### 1.5. Code Splitting Strategies
|
||||
|
||||
* **Dynamic Imports**: Use dynamic imports (`import()`) to load modules on demand.
|
||||
* **Route-Based Splitting**: SvelteKit automatically splits code based on routes.
|
||||
* **Component-Level Splitting**: Split large components into smaller chunks that can be loaded independently.
|
||||
* **Lazy Loading**: Load non-critical components or modules only when needed.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1. Design Patterns Specific to SvelteKit
|
||||
|
||||
* **Form Actions**: Use SvelteKit's form actions for handling form submissions on the server.
|
||||
* **Load Functions**: Utilize `load` functions in `+page.server.ts` and `+layout.server.ts` for data fetching.
|
||||
* **Stores for State Management**: Employ Svelte stores for managing application state.
|
||||
* **Server-Side Rendering (SSR)**: Leverage SSR for improved SEO and initial load performance.
|
||||
* **Progressive Enhancement**: Design applications to work even with JavaScript disabled.
|
||||
|
||||
### 2.2. Recommended Approaches for Common Tasks
|
||||
|
||||
* **Data Fetching**: Use `fetch` API or libraries like `axios` within `load` functions.
|
||||
* **Form Handling**: Use SvelteKit's form actions for server-side validation and processing.
|
||||
* **Authentication**: Implement authentication using libraries like `lucia-auth` or integrate with OAuth providers.
|
||||
* **Authorization**: Implement role-based access control using stores or server-side checks.
|
||||
* **Error Handling**: Use `try...catch` blocks and SvelteKit's `handleError` hook for global error handling.
|
||||
|
||||
### 2.3. Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* **Over-reliance on Global State**: Avoid using global stores for component-specific state.
|
||||
* **Direct DOM Manipulation**: Avoid directly manipulating the DOM; use Svelte's reactivity system instead.
|
||||
* **Large, Unmaintainable Components**: Break down large components into smaller, reusable ones.
|
||||
* **Ignoring Accessibility**: Ensure components are accessible to users with disabilities (ARIA attributes, semantic HTML).
|
||||
* **Unnecessary Re-renders**: Optimize components to avoid unnecessary re-renders.
|
||||
|
||||
### 2.4. State Management Best Practices
|
||||
|
||||
* **Use Svelte Stores**: Svelte stores are the recommended way to manage application state.
|
||||
* **Divide stores according to feature**: Split stores based on logical domain or feature (e.g. UserStore, CartStore).
|
||||
* **Readable and Writable Stores**: Use readable stores for derived state and writable stores for mutable state.
|
||||
* **Custom Stores**: Create custom stores for complex state management logic.
|
||||
|
||||
### 2.5. Error Handling Patterns
|
||||
|
||||
* **`try...catch` Blocks**: Use `try...catch` blocks to handle errors within components and functions.
|
||||
* **`handleError` Hook**: Implement the `handleError` hook in `src/hooks.server.ts` for global error handling.
|
||||
* **Error Boundaries**: Use error boundaries to catch errors in component trees and display fallback UI.
|
||||
* **Logging**: Log errors to a server for monitoring and debugging.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1. Optimization Techniques
|
||||
|
||||
* **Lazy Loading**: Load non-critical resources (images, components) only when needed.
|
||||
* **Code Splitting**: Split code into smaller chunks to reduce initial load time.
|
||||
* **Image Optimization**: Optimize images using tools like `squoosh` or `tinypng`.
|
||||
* **Server-Side Rendering (SSR)**: Use SSR for improved initial load performance and SEO.
|
||||
* **Caching**: Implement caching strategies for data and assets.
|
||||
* **Preload critical assets**: use `<link rel='preload'>` to fetch critical assets earlier
|
||||
|
||||
### 3.2. Memory Management
|
||||
|
||||
* **Avoid Memory Leaks**: Properly clean up resources when components unmount.
|
||||
* **Use WeakRefs**: Use `WeakRefs` for managing objects that might be garbage collected.
|
||||
* **Minimize Object Creation**: Avoid creating unnecessary objects and arrays.
|
||||
* **Properly unsubscrive from stores:** Properly unsubscribe to avoid re-renders when the component is unmounted.
|
||||
|
||||
### 3.3. Rendering Optimization
|
||||
|
||||
* **Tracked values**: Use the `$:` syntax to track dependencies of reactive statements.
|
||||
* **Svelte Compiler**: Utilize Svelte's compiler to optimize component rendering.
|
||||
* **Virtual DOM**: Svelte doesn't use a virtual DOM, so updates are generally very efficient.
|
||||
* **Avoid Unnecessary Re-renders**: Use `{#each}` blocks with keys to optimize list rendering.
|
||||
* **Debouncing and Throttling**: Use debouncing and throttling to limit the frequency of updates.
|
||||
|
||||
### 3.4. Bundle Size Optimization
|
||||
|
||||
* **Tree Shaking**: Ensure unused code is removed during the build process.
|
||||
* **Minification**: Minify JavaScript and CSS files to reduce bundle size.
|
||||
* **Compression**: Compress assets using gzip or Brotli.
|
||||
* **Dependency Analysis**: Analyze dependencies to identify and remove unused libraries.
|
||||
|
||||
### 3.5. Lazy Loading Strategies
|
||||
|
||||
* **Intersection Observer**: Use the Intersection Observer API to detect when elements are visible and load them lazily.
|
||||
* **Dynamic Imports**: Use dynamic imports to load components and modules on demand.
|
||||
* **Placeholder UI**: Display a placeholder UI while resources are loading.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1. Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **Cross-Site Scripting (XSS)**: Sanitize user input to prevent XSS attacks.
|
||||
* **Cross-Site Request Forgery (CSRF)**: Use CSRF tokens to protect against CSRF attacks.
|
||||
* **SQL Injection**: Use parameterized queries or ORMs to prevent SQL injection.
|
||||
* **Authentication and Authorization**: Implement secure authentication and authorization mechanisms.
|
||||
* **Insecure Direct Object References (IDOR)**: Implement proper access controls to prevent unauthorized access to resources.
|
||||
|
||||
### 4.2. Input Validation
|
||||
|
||||
* **Server-Side Validation**: Always validate user input on the server.
|
||||
* **Client-Side Validation**: Use client-side validation for immediate feedback, but never rely on it solely.
|
||||
* **Escape User Input**: Escape user input before rendering it in the DOM.
|
||||
* **Use Validation Libraries**: Use libraries like `zod` or `yup` for input validation.
|
||||
|
||||
### 4.3. Authentication and Authorization Patterns
|
||||
|
||||
* **JWT (JSON Web Tokens)**: Use JWTs for authentication and authorization.
|
||||
* **OAuth 2.0**: Integrate with OAuth providers like Google and Facebook for social login.
|
||||
* **Role-Based Access Control (RBAC)**: Implement RBAC to control access to resources based on user roles.
|
||||
* **Multi-Factor Authentication (MFA)**: Implement MFA for enhanced security.
|
||||
|
||||
### 4.4. Data Protection Strategies
|
||||
|
||||
* **Encryption**: Encrypt sensitive data at rest and in transit.
|
||||
* **Hashing**: Hash passwords using strong hashing algorithms like bcrypt or Argon2.
|
||||
* **Data Masking**: Mask sensitive data in logs and reports.
|
||||
* **Regular Security Audits**: Conduct regular security audits to identify and address vulnerabilities.
|
||||
|
||||
### 4.5. Secure API Communication
|
||||
|
||||
* **HTTPS**: Use HTTPS for all API communication.
|
||||
* **API Keys**: Protect API keys and secrets.
|
||||
* **Rate Limiting**: Implement rate limiting to prevent abuse.
|
||||
* **Input Validation**: Always validate input to your APIs.
|
||||
* **Output Encoding**: Always encode output from your API to prevent injection attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1. Unit Testing Strategies
|
||||
|
||||
* **Test Individual Components**: Write unit tests for individual components in isolation.
|
||||
* **Test Utility Functions**: Write unit tests for utility functions and modules.
|
||||
* **Use Mock Data**: Use mock data for testing components and functions.
|
||||
* **Test Edge Cases**: Test edge cases and error conditions.
|
||||
* **Utilize Svelte Testing Library**: Employ `svelte-testing-library` for testing Svelte components.
|
||||
|
||||
### 5.2. Integration Testing
|
||||
|
||||
* **Test Component Interactions**: Write integration tests to ensure components interact correctly.
|
||||
* **Test Data Flow**: Test the flow of data between components and modules.
|
||||
* **Test API Integrations**: Test integrations with APIs and external services.
|
||||
|
||||
### 5.3. End-to-End Testing
|
||||
|
||||
* **Simulate User Interactions**: Write end-to-end tests to simulate user interactions.
|
||||
* **Test Full Workflows**: Test complete user workflows from start to finish.
|
||||
* **Use Playwright or Cypress**: Use tools like Playwright or Cypress for end-to-end testing.
|
||||
|
||||
### 5.4. Test Organization
|
||||
|
||||
* **Mirror Source Structure**: Organize tests in a directory structure that mirrors the source code.
|
||||
* **Use Descriptive Names**: Use descriptive names for test files and functions.
|
||||
* **Separate Test Environments**: Use separate test environments for unit, integration, and end-to-end tests.
|
||||
|
||||
### 5.5. Mocking and Stubbing
|
||||
|
||||
* **Mock API Calls**: Mock API calls to isolate components during testing.
|
||||
* **Stub External Dependencies**: Stub external dependencies to control their behavior.
|
||||
* **Use Mocking Libraries**: Use libraries like `jest.mock` or `sinon` for mocking and stubbing.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1. Frequent Mistakes Developers Make
|
||||
|
||||
* **Incorrectly Using Reactive Statements**: Not understanding how Svelte's reactivity system works.
|
||||
* **Ignoring Accessibility**: Neglecting accessibility considerations when building components.
|
||||
* **Over-complicating State Management**: Using complex state management solutions when simpler ones would suffice.
|
||||
* **Not Handling Errors Properly**: Ignoring errors or not providing informative error messages.
|
||||
* **Premature Optimization**: Optimizing code before it is necessary.
|
||||
|
||||
### 6.2. Edge Cases to Be Aware Of
|
||||
|
||||
* **Server-Side Rendering Differences**: Be aware of differences between server-side and client-side rendering.
|
||||
* **Browser Compatibility**: Test applications in different browsers to ensure compatibility.
|
||||
* **Network Latency**: Design applications to handle network latency and unreliable connections.
|
||||
* **Memory Constraints**: Consider memory constraints when building large applications.
|
||||
|
||||
### 6.3. Version-Specific Issues
|
||||
|
||||
* **Breaking Changes**: Be aware of breaking changes in new versions of SvelteKit.
|
||||
* **Deprecated Features**: Avoid using deprecated features.
|
||||
* **Upgrade Guides**: Follow upgrade guides when migrating to new versions of SvelteKit.
|
||||
|
||||
### 6.4. Compatibility Concerns
|
||||
|
||||
* **Third-Party Libraries**: Ensure third-party libraries are compatible with SvelteKit.
|
||||
* **Browser Support**: Check browser support for new features and APIs.
|
||||
* **Node.js Version**: Ensure the Node.js version is compatible with SvelteKit.
|
||||
|
||||
### 6.5. Debugging Strategies
|
||||
|
||||
* **Browser Developer Tools**: Use browser developer tools for debugging JavaScript and CSS.
|
||||
* **Svelte Devtools**: Use the Svelte Devtools extension for inspecting Svelte components.
|
||||
* **Logging**: Use `console.log` statements for debugging.
|
||||
* **Debuggers**: Use debuggers like VS Code's debugger for step-by-step debugging.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1. Recommended Development Tools
|
||||
|
||||
* **VS Code**: VS Code is a popular code editor with excellent Svelte and TypeScript support.
|
||||
* **Svelte Devtools**: The Svelte Devtools browser extension allows you to inspect Svelte components.
|
||||
* **ESLint**: ESLint is a linter that helps enforce code style and best practices.
|
||||
* **Prettier**: Prettier is a code formatter that automatically formats code to a consistent style.
|
||||
* **TypeScript**: Using typescript is recommended for type safety.
|
||||
|
||||
### 7.2. Build Configuration
|
||||
|
||||
* **`svelte.config.js`**: Configure SvelteKit using the `svelte.config.js` file.
|
||||
* **Vite**: SvelteKit uses Vite as its build tool.
|
||||
* **Environment Variables**: Use environment variables for configuration settings.
|
||||
* **Adapters**: Use adapters to deploy SvelteKit applications to different environments.
|
||||
|
||||
### 7.3. Linting and Formatting
|
||||
|
||||
* **ESLint**: Configure ESLint to enforce code style and best practices.
|
||||
* **Prettier**: Configure Prettier to automatically format code.
|
||||
* **Husky**: Use Husky to run linters and formatters before committing code.
|
||||
* **Lint Staged**: Use lint-staged to run linters and formatters only on staged files.
|
||||
|
||||
### 7.4. Deployment Best Practices
|
||||
|
||||
* **Choose an Adapter**: Use an adapter like `@sveltejs/adapter-node` or `@sveltejs/adapter-static` to deploy the application.
|
||||
* **Configure Environment Variables**: Configure environment variables for production environments.
|
||||
* **Set Up HTTPS**: Set up HTTPS for secure communication.
|
||||
* **Monitor the Application**: Monitor the application for errors and performance issues.
|
||||
|
||||
### 7.5. CI/CD Integration
|
||||
|
||||
* **Use a CI/CD Pipeline**: Use a CI/CD pipeline to automate the build, test, and deployment process.
|
||||
* **Automated Tests**: Run automated tests in the CI/CD pipeline.
|
||||
* **Automated Deployments**: Automate deployments to production environments.
|
||||
* **Use tools like GitHub Actions, GitLab CI, or CircleCI**
|
||||
@@ -0,0 +1,201 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices and coding standards for Nuxt.js projects, covering code organization, performance, security, testing, and common pitfalls. It aims to ensure maintainable, scalable, and secure Nuxt.js applications.
|
||||
globs: **/*.{vue,js,ts,mjs,mts,jsx,tsx,config.js,config.ts}
|
||||
---
|
||||
- **Enable ESLint support:** Use the `@nuxt/eslint` module for project-aware ESLint configuration. This ensures code quality and consistency.
|
||||
- `npx nuxi module add eslint` to add the module.
|
||||
- Customize the generated `eslint.config.mjs` file as needed.
|
||||
- **Adopt Nuxt.js Modules:** Leverage Nuxt.js modules to encapsulate functionalities and maintain a clean codebase. Explore existing modules before implementing custom solutions (e.g., `@nuxt/auth` for server-side authentication).
|
||||
- **Convention over Configuration:** Adhere to Nuxt.js conventions to simplify development and collaboration. Avoid deviating from conventions unless absolutely necessary.
|
||||
- **Efficiently Utilize Nuxt Layouts:** Create reusable layouts for components shared across multiple pages to ensure consistency and save development time. Layouts are located in the `layouts/` directory.
|
||||
- **Manage State with Pinia:** Use Pinia for state management. Organize store modules based on features or functionalities for better maintainability.
|
||||
- **Divide Pages into Components:** Break down pages into small, reusable components to enhance maintainability, testability, and reusability. Each component should have a single responsibility.
|
||||
- **Leverage Nuxt Plugins Wisely:** Use Nuxt plugins to run code before Vue.js initializes or add global functionality. Be mindful of plugin performance impact. Plugins are located in the `plugins/` directory.
|
||||
- **Optimize for SEO and Performance:** Utilize Nuxt.js's server-side rendering (SSR) for SEO. Implement lazy loading for images and optimize assets to minimize initial load time. Use tools like Lighthouse to identify performance bottlenecks.
|
||||
- **Implement Error Handling and Validation:** Implement robust error handling and validation mechanisms to provide a seamless user experience. Use Nuxt.js middleware to intercept requests and responses for error handling and data validation.
|
||||
- **Document Your Code:** Provide clear and concise documentation for components, modules, and custom functions using tools like JSDoc.
|
||||
- **Embrace Testing:** Write unit tests, integration tests, and end-to-end tests using tools like Jest, Vue Test Utils and Vitest.
|
||||
|
||||
## 1. Code Organization and Structure:
|
||||
|
||||
- **Directory Structure:**
|
||||
- `components/`: Reusable Vue components.
|
||||
- `composables/`: Reusable composable functions.
|
||||
- `layouts/`: Application layouts.
|
||||
- `middleware/`: Route middleware.
|
||||
- `pages/`: Application pages (route definitions).
|
||||
- `plugins/`: Nuxt.js plugins.
|
||||
- `server/`: API routes and server-side logic.
|
||||
- `static/`: Static assets (e.g., images, fonts).
|
||||
- `store/`: Pinia stores (optional, but recommended).
|
||||
- `utils/`: Utility functions.
|
||||
- **File Naming Conventions:**
|
||||
- Components: `PascalCase.vue` (e.g., `MyComponent.vue`)
|
||||
- Composables: `usePascalCase.js` or `usePascalCase.ts` (e.g., `useCounter.js`)
|
||||
- Layouts: `kebab-case.vue` (e.g., `default.vue` or `custom-layout.vue`)
|
||||
- Pages: `kebab-case.vue` (e.g., `index.vue`, `about.vue`, `product-details.vue`)
|
||||
- Plugins: `kebab-case.js` or `kebab-case.ts` (e.g., `analytics.js`)
|
||||
- Stores: `kebab-case.js` or `kebab-case.ts` (e.g., `user-store.js`)
|
||||
- Utility functions: `camelCase.js` or `camelCase.ts` (e.g., `formatDate.js`)
|
||||
- **Module Organization:**
|
||||
- Group related functionalities into separate modules.
|
||||
- Use the `@nuxt/modules` array in `nuxt.config.js` or `nuxt.config.ts` to register modules.
|
||||
- Create custom modules to encapsulate complex logic.
|
||||
- **Component Architecture:**
|
||||
- Favor composition over inheritance.
|
||||
- Use functional components for simple UI elements.
|
||||
- Design components for reusability and testability.
|
||||
- Consider using slots for flexible component composition.
|
||||
- **Code Splitting:**
|
||||
- Utilize dynamic imports for route-based code splitting.
|
||||
- Split large components into smaller chunks using `import()`.
|
||||
- Analyze bundle size with tools like Webpack Bundle Analyzer.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns:
|
||||
|
||||
- **Design Patterns:**
|
||||
- **Composition API:** Use the Composition API for organizing component logic.
|
||||
- **Store Pattern (Pinia):** Implement a centralized state management system with Pinia.
|
||||
- **Middleware Pattern:** Use middleware for authentication, authorization, and data validation.
|
||||
- **Plugin Pattern:** Create plugins for global functionality and third-party library integrations.
|
||||
- **Recommended Approaches:**
|
||||
- **API Communication:** Use the `useFetch` or `useAsyncData` composables for API calls within components.
|
||||
- **Form Handling:** Utilize Vue's built-in form handling features with `v-model` and validation libraries like VeeValidate.
|
||||
- **Authentication:** Implement a secure authentication flow using a library like `@nuxt/auth` or a custom solution.
|
||||
- **Authorization:** Implement role-based access control (RBAC) using middleware and Pinia stores.
|
||||
- **Anti-patterns:**
|
||||
- **Mutating props directly:** Avoid modifying parent component data directly from child components. Use `emit` instead.
|
||||
- **Overusing global state:** Limit the use of global state to essential application data. Consider component-level state for local data.
|
||||
- **Ignoring error handling:** Always handle potential errors in API calls and other asynchronous operations.
|
||||
- **Writing overly complex components:** Break down large components into smaller, more manageable pieces.
|
||||
- **State Management Best Practices:**
|
||||
- **Single Source of Truth:** Maintain a single, consistent source of truth for application state in Pinia stores.
|
||||
- **Immutability:** Treat state as immutable. Use functions to update the store rather than directly manipulating data.
|
||||
- **Clear Naming Conventions:** Use descriptive names for store modules, actions, and mutations.
|
||||
- **Modularization:** Divide stores into modules based on features or functionalities.
|
||||
- **Error Handling Patterns:**
|
||||
- **Centralized Error Handling:** Implement a global error handler to catch unhandled exceptions.
|
||||
- **Error Boundaries:** Use error boundaries to isolate component failures and prevent cascading errors.
|
||||
- **User-Friendly Error Messages:** Provide clear and helpful error messages to users.
|
||||
|
||||
## 3. Performance Considerations:
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Lazy Loading:** Implement lazy loading for images, components, and routes.
|
||||
- **Code Splitting:** Split the application into smaller chunks for faster initial load times.
|
||||
- **Tree Shaking:** Remove unused code during the build process.
|
||||
- **Caching:** Cache API responses and static assets to reduce server load.
|
||||
- **Image Optimization:** Optimize images using tools like `nuxt/image`. Use appropriate image formats (WebP). Resize the image to appropriate size. Consider using a CDN for image delivery.
|
||||
- **Memory Management:**
|
||||
- **Avoid Memory Leaks:** Clean up event listeners and timers when components are unmounted.
|
||||
- **Use Weak References:** Use weak references for DOM elements when possible.
|
||||
- **Minimize Object Creation:** Avoid creating unnecessary objects and arrays.
|
||||
- **Rendering Optimization:**
|
||||
- **Virtualization:** Use virtualization for large lists to improve rendering performance.
|
||||
- **Memoization:** Memoize expensive calculations to avoid redundant computations. Use `computed` properties effectively to avoid unnecessary re-renders.
|
||||
- **Debouncing and Throttling:** Use debouncing and throttling for event handlers to reduce the number of function calls.
|
||||
- **Bundle Size Optimization:**
|
||||
- **Analyze Bundle Size:** Use Webpack Bundle Analyzer to identify large dependencies.
|
||||
- **Remove Unused Dependencies:** Remove unused dependencies to reduce bundle size.
|
||||
- **Use Smaller Alternatives:** Consider using smaller alternatives to large libraries.
|
||||
- **Optimize Dependencies:** Review dependencies and ensure you're using the most efficient ones.
|
||||
- **Lazy Loading Strategies:**
|
||||
- **Route-based Lazy Loading:** Load components only when the corresponding route is accessed.
|
||||
- **Component-based Lazy Loading:** Load components only when they are visible in the viewport.
|
||||
|
||||
## 4. Security Best Practices:
|
||||
|
||||
- **Common Vulnerabilities:**
|
||||
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by properly sanitizing user input and using Vue's built-in HTML escaping.
|
||||
- **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by implementing CSRF tokens.
|
||||
- **SQL Injection:** Avoid raw SQL queries. Use an ORM (Object-Relational Mapper) to prevent SQL injection.
|
||||
- **Authentication and Authorization Flaws:** Implement secure authentication and authorization mechanisms.
|
||||
- **Insecure Direct Object References (IDOR):** Implement proper access control to prevent unauthorized access to resources.
|
||||
- **Input Validation:**
|
||||
- **Server-Side Validation:** Always validate user input on the server-side.
|
||||
- **Client-Side Validation:** Provide client-side validation for a better user experience (but don't rely on it as the sole source of validation).
|
||||
- **Sanitize Input:** Sanitize user input to remove potentially harmful characters.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- **JWT (JSON Web Tokens):** Use JWT for authentication and authorization.
|
||||
- **OAuth 2.0:** Implement OAuth 2.0 for third-party authentication.
|
||||
- **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
|
||||
- **Data Protection Strategies:**
|
||||
- **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
- **Hashing:** Hash passwords and other sensitive data using strong hashing algorithms.
|
||||
- **Data Masking:** Mask sensitive data in logs and other non-production environments.
|
||||
- **Secure API Communication:**
|
||||
- **HTTPS:** Always use HTTPS for API communication.
|
||||
- **API Rate Limiting:** Implement API rate limiting to prevent abuse.
|
||||
- **Authentication and Authorization:** Require authentication and authorization for all API endpoints.
|
||||
|
||||
## 5. Testing Approaches:
|
||||
|
||||
- **Unit Testing:**
|
||||
- **Test Individual Components:** Test individual components in isolation.
|
||||
- **Mock Dependencies:** Mock external dependencies to isolate components during testing.
|
||||
- **Verify Component Behavior:** Verify that components render correctly and behave as expected.
|
||||
- **Integration Testing:**
|
||||
- **Test Component Interactions:** Test the interactions between components.
|
||||
- **Test Data Flow:** Test the data flow between components and stores.
|
||||
- **Test API Integrations:** Test the integration with external APIs.
|
||||
- **End-to-End Testing:**
|
||||
- **Simulate User Interactions:** Simulate user interactions to test the application's functionality.
|
||||
- **Test the Entire Application Flow:** Test the entire application flow from start to finish.
|
||||
- **Use a Browser Automation Tool:** Use a browser automation tool like Cypress or Playwright.
|
||||
- **Test Organization:**
|
||||
- **Organize Tests by Feature:** Organize tests by feature or functionality.
|
||||
- **Use Descriptive Test Names:** Use descriptive test names to clearly indicate what each test is testing.
|
||||
- **Keep Tests Isolated:** Keep tests isolated from each other to avoid interference.
|
||||
- **Mocking and Stubbing:**
|
||||
- **Use Mock Objects:** Use mock objects to replace external dependencies during testing.
|
||||
- **Use Stubs:** Use stubs to replace complex functions with simplified versions.
|
||||
- **Avoid Over-Mocking:** Avoid mocking too much code, as this can make tests less effective.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas:
|
||||
|
||||
- **Frequent Mistakes:**
|
||||
- **Incorrect `this` Context:** Be mindful of the `this` context in Vue components and use arrow functions or `bind` to maintain the correct context.
|
||||
- **Asynchronous Data Handling:** Properly handle asynchronous data loading with `async/await` or Promises.
|
||||
- **Forgetting to Unsubscribe:** Unsubscribe from event listeners and timers when components are unmounted to prevent memory leaks.
|
||||
- **Overusing `forceUpdate`:** Avoid using `forceUpdate` unless absolutely necessary, as it can negatively impact performance.
|
||||
- **Edge Cases:**
|
||||
- **Server-Side Rendering (SSR):** Be aware of the differences between client-side and server-side rendering.
|
||||
- **Browser Compatibility:** Test the application in different browsers to ensure compatibility.
|
||||
- **Accessibility:** Consider accessibility when designing and developing the application.
|
||||
- **Version-Specific Issues:**
|
||||
- **Nuxt 2 vs Nuxt 3:** Be aware of the differences between Nuxt 2 and Nuxt 3.
|
||||
- **Vue 2 vs Vue 3:** Be aware of the differences between Vue 2 and Vue 3.
|
||||
- **Dependency Updates:** Carefully review dependency updates for potential breaking changes.
|
||||
- **Compatibility Concerns:**
|
||||
- **Browser Support:** Ensure compatibility with the target browsers.
|
||||
- **Device Compatibility:** Test the application on different devices.
|
||||
- **Operating System Compatibility:** Ensure compatibility with the target operating systems.
|
||||
- **Debugging Strategies:**
|
||||
- **Use Browser Developer Tools:** Use browser developer tools to inspect the application's state and network activity.
|
||||
- **Use Vue Devtools:** Use Vue Devtools to inspect Vue components and data.
|
||||
- **Use Logging:** Use logging to track the application's behavior.
|
||||
|
||||
## 7. Tooling and Environment:
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **VS Code:** Visual Studio Code is a popular code editor with excellent Vue.js support.
|
||||
- **Vue Devtools:** Vue Devtools is a browser extension that provides debugging tools for Vue.js applications.
|
||||
- **ESLint:** ESLint is a linter that enforces coding standards.
|
||||
- **Prettier:** Prettier is a code formatter that automatically formats code.
|
||||
- **Build Configuration:**
|
||||
- **`nuxt.config.js` or `nuxt.config.ts`:** Configure the application's build settings in `nuxt.config.js` or `nuxt.config.ts`.
|
||||
- **Webpack:** Nuxt uses Webpack to bundle the application.
|
||||
- **Vite:** Nuxt 3 uses Vite to bundle the application by default, providing faster build and development times.
|
||||
- **Linting and Formatting:**
|
||||
- **ESLint:** Use ESLint to enforce coding standards.
|
||||
- **Prettier:** Use Prettier to automatically format code.
|
||||
- **Husky:** Use Husky to run linters and formatters before commits.
|
||||
- **Deployment Best Practices:**
|
||||
- **Server-Side Rendering (SSR):** Deploy the application to a server that supports SSR.
|
||||
- **Static Site Generation (SSG):** Generate a static site for content-heavy applications.
|
||||
- **CDN:** Use a CDN to deliver static assets.
|
||||
- **CI/CD Integration:**
|
||||
- **Continuous Integration (CI):** Use a CI tool like Jenkins, GitLab CI, or GitHub Actions to automate the build and testing process.
|
||||
- **Continuous Deployment (CD):** Use a CD tool to automate the deployment process.
|
||||
|
||||
By following these best practices, you can build robust, maintainable, and scalable Nuxt.js applications.
|
||||
@@ -0,0 +1,298 @@
|
||||
---
|
||||
description: Comprehensive guidelines for Vue.js development, covering code structure, performance, security, testing, and tooling best practices. This rule provides actionable guidance to enhance code quality, maintainability, and developer productivity in Vue.js projects.
|
||||
globs: **/*.vue, **/*.js, **/*.ts
|
||||
---
|
||||
# Vue.js Best Practices and Coding Standards
|
||||
|
||||
This document outlines best practices for Vue.js development, covering various aspects to ensure high-quality, maintainable, and performant code.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1. Directory Structure
|
||||
|
||||
* **Component-Based Structure:** Organize components into logical folders based on their functionality or feature. This improves code readability and maintainability.
|
||||
|
||||
src/
|
||||
├── components/
|
||||
│ ├── Button/
|
||||
│ │ ├── Button.vue
|
||||
│ │ └── Button.spec.js
|
||||
│ ├── Input/
|
||||
│ │ ├── Input.vue
|
||||
│ │ └── Input.spec.js
|
||||
│ └── ...
|
||||
├── views/
|
||||
│ ├── Home.vue
|
||||
│ ├── About.vue
|
||||
│ └── ...
|
||||
├── services/
|
||||
│ ├── api.js
|
||||
│ └── auth.js
|
||||
├── store/
|
||||
│ ├── index.js # Vuex store
|
||||
│ ├── modules/
|
||||
│ │ ├── user.js
|
||||
│ │ └── ...
|
||||
├── App.vue
|
||||
└── main.js
|
||||
|
||||
* **Feature-Based Structure:** Alternatively, organize files by feature, grouping components, routes, and store modules related to a specific feature.
|
||||
|
||||
src/
|
||||
├── features/
|
||||
│ ├── user-profile/
|
||||
│ │ ├── components/
|
||||
│ │ │ ├── UserProfile.vue
|
||||
│ │ │ └── ...
|
||||
│ │ ├── routes.js
|
||||
│ │ ├── store.js
|
||||
│ │ └── ...
|
||||
│ ├── shopping-cart/
|
||||
│ │ ├── ...
|
||||
│ └── ...
|
||||
├── App.vue
|
||||
└── main.js
|
||||
|
||||
|
||||
### 1.2. File Naming Conventions
|
||||
|
||||
* **Component Files:** Use PascalCase for component file names (e.g., `MyComponent.vue`).
|
||||
* **Other Files:** Use camelCase or kebab-case for other JavaScript/TypeScript files (e.g., `apiService.js`, `my-helper.js`).
|
||||
* **Consistency:** Maintain a consistent naming convention throughout the project.
|
||||
|
||||
### 1.3. Module Organization
|
||||
|
||||
* **ES Modules:** Utilize ES modules (`import`/`export`) for modular code organization.
|
||||
* **Single Responsibility Principle:** Each module should have a single, well-defined responsibility.
|
||||
* **Avoid Circular Dependencies:** Prevent circular dependencies between modules to avoid unexpected behavior and improve maintainability.
|
||||
|
||||
### 1.4. Component Architecture
|
||||
|
||||
* **Component Composition:** Favor component composition over inheritance for increased flexibility and reusability.
|
||||
* **Presentational and Container Components:** Separate presentational (dumb) components from container (smart) components. Presentational components focus on rendering UI, while container components handle data fetching and logic.
|
||||
* **Single File Components (SFCs):** Leverage Vue's SFCs for encapsulating component logic, template, and styling.
|
||||
|
||||
### 1.5. Code Splitting Strategies
|
||||
|
||||
* **Route-Based Splitting:** Use dynamic imports and Vue's `async` component feature to split the application into chunks based on routes.
|
||||
* **Component-Based Splitting:** Split large components into smaller, lazy-loaded components to improve initial load time.
|
||||
* **Vendor Splitting:** Separate vendor dependencies into a separate chunk to allow for browser caching and prevent unnecessary reloads.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1. Design Patterns Specific to Vue
|
||||
|
||||
* **Provide/Inject:** Use `provide` and `inject` for dependency injection between components, especially when dealing with deeply nested components.
|
||||
* **Renderless Components:** Create renderless components that encapsulate logic and provide data to be rendered by slot-using components.
|
||||
* **Higher-Order Components (HOCs):** Use HOCs to reuse component logic or add functionality to existing components.
|
||||
|
||||
### 2.2. Recommended Approaches for Common Tasks
|
||||
|
||||
* **Form Handling:** Use `v-model` for two-way data binding in forms. Consider using a form validation library like Vuelidate or VeeValidate for robust form validation.
|
||||
* **API Requests:** Use a dedicated service module for handling API requests. Use `async/await` for cleaner asynchronous code.
|
||||
* **State Management:** Utilize Vuex for centralized state management in larger applications. For simpler applications, consider using Vue's reactivity system directly or a lightweight state management solution like Pinia.
|
||||
* **Event Handling:** Use component events (`$emit`) for communication between parent and child components. For communication between unrelated components, use a global event bus (with caution) or a state management solution.
|
||||
|
||||
### 2.3. Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* **Mutating Props Directly:** Avoid mutating props directly within a component. Instead, emit an event to the parent component to update the prop value.
|
||||
* **Overusing Global State:** Avoid storing too much data in global state. Use local component state whenever possible.
|
||||
* **Direct DOM Manipulation:** Avoid directly manipulating the DOM using `document` APIs. Use Vue's template directives and component APIs to update the DOM reactively.
|
||||
* **Magic Numbers and Strings:** Avoid using magic numbers and strings directly in the code. Use constants to improve readability and maintainability.
|
||||
* **Complex Computed Properties:** Keep computed properties simple and focused. Complex computations should be moved to methods or utility functions.
|
||||
|
||||
### 2.4. State Management Best Practices
|
||||
|
||||
* **Single Source of Truth:** Maintain a single source of truth for application state using Vuex or Pinia.
|
||||
* **Mutations for State Updates:** Only use mutations to update the state in Vuex. Mutations should be synchronous and atomic.
|
||||
* **Actions for Asynchronous Operations:** Use actions to handle asynchronous operations like API requests. Actions can commit mutations to update the state.
|
||||
* **Getters for Derived State:** Use getters to derive state from the store. Getters should be pure functions and should not modify the state.
|
||||
* **Modularity:** Organize the store into modules to improve maintainability and scalability.
|
||||
|
||||
### 2.5. Error Handling Patterns
|
||||
|
||||
* **Centralized Error Handling:** Implement a centralized error handling mechanism to catch and log errors consistently.
|
||||
* **Error Boundary Components:** Use error boundary components to catch errors within specific parts of the application and prevent crashes.
|
||||
* **User-Friendly Error Messages:** Provide user-friendly error messages to guide users when errors occur.
|
||||
* **Logging:** Log errors to a server or error tracking service for monitoring and debugging.
|
||||
* **Try-Catch Blocks:** Use `try-catch` blocks to handle potential errors in asynchronous operations or complex computations.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1. Optimization Techniques
|
||||
|
||||
* **Virtual DOM Optimization:** Vue's virtual DOM implementation is already highly optimized, but avoid unnecessary re-renders by using `v-if` instead of `v-show` when elements are rarely displayed.
|
||||
* **Computed Properties and Watchers:** Use computed properties and watchers judiciously. Avoid performing expensive computations in computed properties that are frequently re-evaluated. Debounce or throttle watchers to limit the number of updates.
|
||||
* **List Rendering Optimization:** Use the `:key` attribute when rendering lists with `v-for` to help Vue track changes efficiently. Ensure the keys are unique and stable.
|
||||
* **Functional Components:** Use functional components for simple, stateless components to improve rendering performance.
|
||||
* **Avoid Inline Templates:** Use pre-compiled templates in single-file components instead of inline templates (using `<script type="text/x-template">`) for better performance.
|
||||
|
||||
### 3.2. Memory Management
|
||||
|
||||
* **Remove Event Listeners:** When a component is destroyed, remove any event listeners that were added manually (e.g., using `addEventListener`).
|
||||
* **Unsubscribe from Observables:** If using RxJS or other observable libraries, unsubscribe from observables when the component is destroyed to prevent memory leaks.
|
||||
* **Release References:** Release references to large objects or data structures when they are no longer needed to allow the garbage collector to reclaim memory.
|
||||
|
||||
### 3.3. Rendering Optimization
|
||||
|
||||
* **Asynchronous Updates:** Use `Vue.nextTick()` or `setTimeout()` to defer updates that are not immediately needed, allowing the browser to complete rendering tasks.
|
||||
* **Debouncing and Throttling:** Debounce or throttle event handlers that trigger frequent updates to prevent excessive re-renders.
|
||||
* **`v-once` Directive:** Use the `v-once` directive for elements that will never change to improve rendering performance.
|
||||
* **Avoid Deeply Nested Components:** Deeply nested component hierarchies can impact rendering performance. Consider flattening the hierarchy or using techniques like scoped slots to optimize rendering.
|
||||
|
||||
### 3.4. Bundle Size Optimization
|
||||
|
||||
* **Code Splitting:** Implement code splitting to reduce the initial bundle size and improve loading time.
|
||||
* **Tree Shaking:** Use a modern build tool like Webpack or Rollup to perform tree shaking and remove unused code from the final bundle.
|
||||
* **Minification and Compression:** Minify and compress the code to reduce the bundle size.
|
||||
* **Image Optimization:** Optimize images by compressing them and using appropriate formats (e.g., WebP) to reduce file sizes.
|
||||
* **Lazy Loading:** Lazy load images, components, and other resources to improve initial load time.
|
||||
|
||||
### 3.5. Lazy Loading Strategies
|
||||
|
||||
* **Lazy Loading Components:** Use dynamic imports to lazy load components only when they are needed.
|
||||
* **Lazy Loading Images:** Use a lazy loading library to load images only when they are visible in the viewport.
|
||||
* **Lazy Loading Routes:** Lazy load routes using Vue Router's `component: () => import('./MyComponent.vue')` syntax.
|
||||
|
||||
## 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 using Vue's built-in template directives, which automatically escape HTML entities.
|
||||
* **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by implementing CSRF tokens in forms and API requests.
|
||||
* **SQL Injection:** Prevent SQL injection attacks by using parameterized queries or an ORM with built-in protection.
|
||||
* **Man-in-the-Middle (MitM) Attacks:** Use HTTPS to encrypt communication between the client and server and protect against MitM attacks.
|
||||
* **Clickjacking:** Prevent clickjacking attacks by setting the `X-Frame-Options` header to `DENY` or `SAMEORIGIN`.
|
||||
|
||||
### 4.2. Input Validation
|
||||
|
||||
* **Server-Side Validation:** Always perform server-side validation to ensure data integrity and prevent malicious input.
|
||||
* **Client-Side Validation:** Implement client-side validation to provide immediate feedback to users and reduce server load. Use libraries like Vuelidate or VeeValidate.
|
||||
* **Sanitization:** Sanitize user input to remove potentially harmful characters or code.
|
||||
|
||||
### 4.3. Authentication and Authorization Patterns
|
||||
|
||||
* **JSON Web Tokens (JWT):** Use JWTs for authentication and authorization. Store JWTs securely in the client-side (e.g., using HTTP-only cookies or local storage with encryption).
|
||||
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of the application based on user roles.
|
||||
* **OAuth 2.0:** Use OAuth 2.0 for third-party authentication and authorization.
|
||||
* **Secure Password Storage:** Store passwords securely using a strong hashing algorithm like bcrypt or Argon2.
|
||||
|
||||
### 4.4. Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data both in transit and at rest.
|
||||
* **Data Masking:** Mask sensitive data in the UI to prevent unauthorized access.
|
||||
* **Data Minimization:** Collect only the necessary data and avoid storing sensitive data unnecessarily.
|
||||
* **Regular Security Audits:** Conduct regular security audits to identify and address potential vulnerabilities.
|
||||
|
||||
### 4.5. Secure API Communication
|
||||
|
||||
* **HTTPS:** Use HTTPS for all API communication.
|
||||
* **API Authentication:** Implement authentication for all API endpoints using JWTs or other authentication mechanisms.
|
||||
* **Rate Limiting:** Implement rate limiting to prevent abuse and denial-of-service attacks.
|
||||
* **Input Validation:** Validate all API input to prevent injection attacks.
|
||||
* **Output Encoding:** Encode API output to prevent XSS attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1. Unit Testing Strategies
|
||||
|
||||
* **Component Testing:** Write unit tests for individual Vue components to verify their behavior in isolation. Use a testing library like Jest or Mocha with Vue Test Utils.
|
||||
* **Function Testing:** Write unit tests for utility functions and other non-component code.
|
||||
* **Test-Driven Development (TDD):** Consider using TDD to write tests before writing the code.
|
||||
|
||||
### 5.2. Integration Testing
|
||||
|
||||
* **Component Integration:** Write integration tests to verify the interaction between multiple components.
|
||||
* **Module Integration:** Write integration tests to verify the interaction between different modules of the application.
|
||||
* **End-to-End Integration:** Write end-to-end integration tests to verify the entire application flow from the user's perspective. Tools like Cypress, Playwright, or Selenium can be used for E2E testing.
|
||||
|
||||
### 5.3. End-to-End Testing
|
||||
|
||||
* **User Flow Testing:** Simulate user flows to test the application's functionality from end to end.
|
||||
* **Visual Regression Testing:** Use visual regression testing to detect unintended visual changes in the UI.
|
||||
* **Accessibility Testing:** Test the application's accessibility to ensure it is usable by people with disabilities.
|
||||
|
||||
### 5.4. Test Organization
|
||||
|
||||
* **Test Suites:** Organize tests into suites based on the component or module being tested.
|
||||
* **Test Cases:** Write clear and concise test cases with descriptive names.
|
||||
* **Arrange-Act-Assert:** Follow the Arrange-Act-Assert pattern in each test case.
|
||||
|
||||
### 5.5. Mocking and Stubbing
|
||||
|
||||
* **Mock Dependencies:** Mock external dependencies like API services or third-party libraries to isolate the code being tested.
|
||||
* **Stub Component Behavior:** Stub the behavior of child components to focus on testing the parent component's logic.
|
||||
* **Use Mocking Libraries:** Use a mocking library like Jest's `jest.fn()` to create mock functions and objects.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1. Frequent Mistakes Developers Make
|
||||
|
||||
* **Forgetting to Use `:key` in `v-for`:** Always use the `:key` attribute when rendering lists with `v-for` to ensure efficient DOM updates.
|
||||
* **Incorrectly Using `v-if` and `v-show`:** Understand the difference between `v-if` and `v-show` and use them appropriately. `v-if` conditionally renders the element, while `v-show` toggles the element's visibility.
|
||||
* **Mutating Props Directly:** Avoid mutating props directly. Emit an event to the parent component to update the prop value.
|
||||
* **Not Handling Edge Cases:** Consider edge cases and write tests to cover them.
|
||||
|
||||
### 6.2. Edge Cases to Be Aware Of
|
||||
|
||||
* **Empty Arrays or Objects:** Handle cases where data is empty or null.
|
||||
* **Unexpected API Responses:** Handle cases where the API returns an error or unexpected data.
|
||||
* **User Input Errors:** Handle cases where the user enters invalid or malicious input.
|
||||
|
||||
### 6.3. Version-Specific Issues
|
||||
|
||||
* **Breaking Changes:** Be aware of breaking changes in new Vue.js versions and update the code accordingly.
|
||||
* **Deprecated APIs:** Avoid using deprecated APIs and migrate to the recommended alternatives.
|
||||
* **Compatibility Issues:** Ensure compatibility with the target browsers and devices.
|
||||
|
||||
### 6.4. Compatibility Concerns
|
||||
|
||||
* **Browser Compatibility:** Test the application in different browsers and devices to ensure compatibility.
|
||||
* **Accessibility:** Ensure the application is accessible to users with disabilities.
|
||||
* **Responsive Design:** Implement responsive design to ensure the application looks good on different screen sizes.
|
||||
|
||||
### 6.5. Debugging Strategies
|
||||
|
||||
* **Vue Devtools:** Use the Vue Devtools browser extension to inspect components, state, and events.
|
||||
* **Console Logging:** Use `console.log()` to debug code and track variables.
|
||||
* **Debugger Statements:** Use `debugger` statements to pause the execution of code and inspect variables.
|
||||
* **Error Logging:** Log errors to a server or error tracking service for monitoring and debugging.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1. Recommended Development Tools
|
||||
|
||||
* **VS Code with Vetur or Volar:** Use VS Code with the Vetur (Vue tooling) or Volar extension for syntax highlighting, code completion, and other features.
|
||||
* **Vue CLI:** Use Vue CLI for scaffolding projects, building, and serving the application.
|
||||
* **Vue Devtools:** Use the Vue Devtools browser extension for debugging Vue applications.
|
||||
* **ESLint:** Use ESLint with the `eslint-plugin-vue` plugin for linting Vue code.
|
||||
* **Prettier:** Use Prettier for formatting Vue code.
|
||||
|
||||
### 7.2. Build Configuration
|
||||
|
||||
* **Webpack or Rollup:** Use Webpack or Rollup for building the application.
|
||||
* **Babel:** Use Babel for transpiling JavaScript code to ensure compatibility with older browsers.
|
||||
* **PostCSS:** Use PostCSS for processing CSS code and adding vendor prefixes.
|
||||
|
||||
### 7.3. Linting and Formatting
|
||||
|
||||
* **ESLint:** Configure ESLint with the `eslint-plugin-vue` plugin to enforce coding standards and prevent errors.
|
||||
* **Prettier:** Configure Prettier to automatically format code according to a consistent style.
|
||||
* **Husky and lint-staged:** Use Husky and lint-staged to run linters and formatters before committing code.
|
||||
|
||||
### 7.4. Deployment Best Practices
|
||||
|
||||
* **Build for Production:** Build the application for production with the `--mode production` flag.
|
||||
* **Optimize Assets:** Optimize assets like images and fonts to reduce file sizes.
|
||||
* **Use a CDN:** Use a content delivery network (CDN) to serve static assets.
|
||||
* **Configure Caching:** Configure caching headers to improve performance.
|
||||
* **Use HTTPS:** Use HTTPS for all communication.
|
||||
|
||||
### 7.5. CI/CD Integration
|
||||
|
||||
* **Automated Builds:** Configure a CI/CD pipeline to automatically build and deploy the application whenever changes are pushed to the repository.
|
||||
* **Automated Testing:** Run automated tests in the CI/CD pipeline to ensure code quality.
|
||||
* **Automated Deployment:** Automate the deployment process to reduce manual effort and prevent errors.
|
||||
|
||||
|
||||
By following these best practices, you can create high-quality, maintainable, and performant Vue.js applications.
|
||||
@@ -0,0 +1,114 @@
|
||||
---
|
||||
description: This rule provides best practices and coding standards for Vue 3 projects, covering code organization, performance, security, testing, tooling, and common pitfalls to ensure maintainable and efficient applications. It aims to guide developers in writing high-quality Vue 3 code.
|
||||
globs: **/*.vue
|
||||
---
|
||||
- **Code Organization and Structure**:
|
||||
- **Directory Structure**: Adopt a feature-based directory structure. Group related files (components, stores, utilities) within feature-specific directories rather than separating by file type. This enhances maintainability and discoverability.
|
||||
- Example:
|
||||
|
||||
src/
|
||||
components/
|
||||
MyComponent.vue
|
||||
...
|
||||
views/
|
||||
MyView.vue
|
||||
...
|
||||
features/
|
||||
user-profile/
|
||||
components/
|
||||
UserProfileCard.vue
|
||||
composables/
|
||||
useUserProfileData.js
|
||||
store/
|
||||
userProfile.js
|
||||
...
|
||||
|
||||
- **File Naming Conventions**: Use PascalCase for component file names (e.g., `MyComponent.vue`). Use camelCase for variable and function names (e.g., `myVariable`, `myFunction`). Use kebab-case for component selectors in templates (e.g., `<my-component>`).
|
||||
- **Module Organization**: Utilize ES modules (`import`/`export`) for modularity and code reusability. Group related functions and components into modules.
|
||||
- **Component Architecture**: Favor a component-based architecture. Design components to be small, reusable, and composable. Use props for data input and events for data output. Consider using a component library (e.g., Vuetify, Element Plus) for pre-built components.
|
||||
- **Code Splitting Strategies**: Implement lazy loading for components and routes to reduce initial bundle size. Use dynamic imports for on-demand loading of modules.
|
||||
- Example:
|
||||
javascript
|
||||
// Route-based code splitting
|
||||
const routes = [
|
||||
{
|
||||
path: '/about',
|
||||
component: () => import('./views/About.vue')
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
- **Common Patterns and Anti-patterns**:
|
||||
- **Design Patterns**: Apply common design patterns such as composition API, provider/inject, and observer pattern where applicable.
|
||||
- **Composition API**: Organize component logic into composable functions for reusability and maintainability.
|
||||
- **Provider/Inject**: Use `provide` and `inject` to share data between components without prop drilling.
|
||||
- **Recommended Approaches**: Utilize `v-model` for two-way data binding, computed properties for derived state, and watchers for side effects. Use the Composition API for enhanced code organization and reusability.
|
||||
- **Anti-patterns and Code Smells**: Avoid directly mutating props. Avoid excessive use of global variables. Avoid complex logic within templates. Avoid tight coupling between components. Avoid over-engineering solutions.
|
||||
- **State Management**: Choose a state management solution (e.g., Vuex, Pinia) for complex applications. Favor Pinia for Vue 3 due to its simpler API and improved TypeScript support. Decouple components from state management logic using actions and mutations.
|
||||
- **Error Handling**: Implement global error handling using `app.config.errorHandler`. Use `try...catch` blocks for handling synchronous errors. Utilize `Promise.catch` for handling asynchronous errors. Provide user-friendly error messages.
|
||||
- Example:
|
||||
javascript
|
||||
// Global error handler
|
||||
app.config.errorHandler = (err, vm, info) => {
|
||||
console.error('Global error:', err, info);
|
||||
// Report error to server or display user-friendly message
|
||||
}
|
||||
|
||||
|
||||
- **Performance Considerations**:
|
||||
- **Optimization Techniques**: Use `v-once` for static content. Use `v-memo` to memoize parts of the template. Use `key` attribute for `v-for` loops to improve rendering performance.
|
||||
- **Memory Management**: Avoid creating memory leaks by properly cleaning up event listeners and timers. Use `onBeforeUnmount` lifecycle hook to release resources.
|
||||
- **Rendering Optimization**: Use virtual DOM efficiently. Minimize unnecessary re-renders by using `ref` and `reactive` appropriately. Use `shouldUpdate` hook in functional components to control updates.
|
||||
- **Bundle Size Optimization**: Use code splitting, tree shaking, and minification to reduce bundle size. Remove unused dependencies. Use smaller alternative libraries where possible.
|
||||
- **Lazy Loading**: Implement lazy loading for images, components, and routes. Use `IntersectionObserver` API for lazy loading images.
|
||||
|
||||
- **Security Best Practices**:
|
||||
- **Common Vulnerabilities**: Prevent Cross-Site Scripting (XSS) attacks by sanitizing user input. Prevent Cross-Site Request Forgery (CSRF) attacks by using CSRF tokens. Prevent SQL injection attacks by using parameterized queries.
|
||||
- **Input Validation**: Validate user input on both client-side and server-side. Use appropriate data types and formats. Escape special characters.
|
||||
- **Authentication and Authorization**: Implement secure authentication and authorization mechanisms. Use HTTPS to encrypt communication. Store passwords securely using hashing and salting.
|
||||
- **Data Protection**: Protect sensitive data using encryption. Avoid storing sensitive data in client-side storage. Follow privacy best practices.
|
||||
- **Secure API Communication**: Use HTTPS for API communication. Validate API responses. Implement rate limiting to prevent abuse.
|
||||
|
||||
- **Testing Approaches**:
|
||||
- **Unit Testing**: Write unit tests for individual components, functions, and modules. Use Jest or Vitest as a test runner. Mock dependencies to isolate units of code.
|
||||
- **Integration Testing**: Write integration tests to verify the interaction between components and modules. Use Vue Test Utils for component testing.
|
||||
- **End-to-End Testing**: Write end-to-end tests to simulate user interactions and verify the application's overall functionality. Use Cypress or Playwright for end-to-end testing.
|
||||
- **Test Organization**: Organize tests into separate directories based on the component or module being tested. Use descriptive test names.
|
||||
- **Mocking and Stubbing**: Use mocks and stubs to isolate units of code and simulate dependencies. Use `jest.mock` or `vi.mock` for mocking modules.
|
||||
|
||||
- **Common Pitfalls and Gotchas**:
|
||||
- **Frequent Mistakes**: Forgetting to register components. Incorrectly using `v-if` and `v-show`. Mutating props directly. Not handling asynchronous operations correctly. Ignoring error messages.
|
||||
- **Edge Cases**: Handling empty arrays or objects. Dealing with browser compatibility issues. Managing state in complex components.
|
||||
- **Version-Specific Issues**: Being aware of breaking changes between Vue 2 and Vue 3. Using deprecated APIs.
|
||||
- **Compatibility Concerns**: Ensuring compatibility with different browsers and devices. Testing on different screen sizes and resolutions.
|
||||
- **Debugging Strategies**: Using Vue Devtools for debugging. Using `console.log` statements for inspecting variables. Using a debugger for stepping through code.
|
||||
|
||||
- **Tooling and Environment**:
|
||||
- **Recommended Development Tools**: Use VS Code with the Volar extension for Vue 3 development. Use Vue CLI or Vite for project scaffolding. Use Vue Devtools for debugging.
|
||||
- **Build Configuration**: Configure Webpack or Rollup for building the application. Optimize build settings for production. Use environment variables for configuration.
|
||||
- **Linting and Formatting**: Use ESLint with the `eslint-plugin-vue` plugin for linting Vue code. Use Prettier for code formatting. Configure linting and formatting rules to enforce code style.
|
||||
- **Deployment Best Practices**: Use a CDN for serving static assets. Use server-side rendering (SSR) or pre-rendering for improved SEO and performance. Deploy to a reliable hosting platform.
|
||||
- **CI/CD Integration**: Integrate linting, testing, and building into the CI/CD pipeline. Use automated deployment tools. Monitor application performance and errors.
|
||||
|
||||
- **Additional Best Practices**:
|
||||
- **Accessibility (A11y)**: Ensure components are accessible by using semantic HTML, providing ARIA attributes where necessary, and testing with screen readers.
|
||||
- **Internationalization (i18n)**: Implement i18n from the start if multilingual support is required. Use a library like `vue-i18n` to manage translations.
|
||||
- **Documentation**: Document components and composables using JSDoc or similar tools. Generate documentation automatically using tools like Storybook.
|
||||
|
||||
- **Vue 3 Specific Recommendations**:
|
||||
- **TypeScript**: Use TypeScript for improved type safety and code maintainability. Define component props and emits with type annotations.
|
||||
- **Teleport**: Use the `Teleport` component to render content outside the component's DOM hierarchy, useful for modals and tooltips.
|
||||
- **Suspense**: Use the `Suspense` component to handle asynchronous dependencies gracefully, providing fallback content while waiting for data to load.
|
||||
|
||||
- **Naming Conventions**:
|
||||
- Components: PascalCase (e.g., `MyComponent.vue`)
|
||||
- Variables/Functions: camelCase (e.g., `myVariable`, `myFunction`)
|
||||
- Props/Events: camelCase (e.g., `myProp`, `myEvent`)
|
||||
- Directives: kebab-case (e.g., `v-my-directive`)
|
||||
|
||||
- **Composition API Best Practices**:
|
||||
- **Reactive Refs**: Use `ref` for primitive values and `reactive` for objects.
|
||||
- **Readonly Refs**: Use `readonly` to prevent accidental mutations of reactive data.
|
||||
- **Computed Properties**: Use `computed` for derived state and avoid complex logic within templates.
|
||||
- **Lifecycle Hooks**: Use `onMounted`, `onUpdated`, `onUnmounted`, etc., to manage component lifecycle events.
|
||||
- **Watchers**: Use `watch` for reacting to reactive data changes and performing side effects.
|
||||
Reference in New Issue
Block a user