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:
sanjeed5
2025-02-27 16:58:58 +05:30
parent 676f3376bf
commit 5068ef1d22
88 changed files with 20037 additions and 0 deletions
+201
View File
@@ -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.
+298
View File
@@ -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.
+114
View File
@@ -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.