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,150 @@
|
||||
---
|
||||
description: Enforces best practices, coding standards, and performance considerations for Electron development. Covers code structure, security, testing, and common pitfalls to ensure robust and maintainable applications.
|
||||
globs: **/*.{js,jsx,ts,tsx,html,css,scss,mjs,cjs}
|
||||
---
|
||||
- **General Practices**
|
||||
- Adhere to the official Electron coding style guide. Run `npm run lint` to detect style issues using `cpplint` and `eslint`.
|
||||
- Aim for line lengths between 80 and 100 characters for readability.
|
||||
- Use `sh` instead of `cmd` in code blocks for cross-platform compatibility in documentation.
|
||||
- Select the appropriate Electron version based on project needs and compatibility with dependencies.
|
||||
- Always update electron to the latest stable version to receive security fixes and performance improvements.
|
||||
|
||||
- **Code Organization and Structure**
|
||||
- **Directory Structure:**
|
||||
- Structure your project logically. Consider using a structure like:
|
||||
|
||||
electron-app/
|
||||
├── main.js # Main process entry point
|
||||
├── preload.js # Preload script (for specific renderers if needed)
|
||||
├── renderer/
|
||||
│ ├── index.html # Main HTML file
|
||||
│ ├── script.js # Renderer process scripts
|
||||
│ ├── style.css # Stylesheets
|
||||
│ └── components/ # Reusable components (if applicable)
|
||||
├── assets/ # Static assets (images, fonts, etc.)
|
||||
├── package.json
|
||||
└── electron-builder.yml # Electron Builder configuration
|
||||
|
||||
- Organize your code into modules based on functionality (e.g., authentication, data handling, UI components).
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive and consistent naming conventions.
|
||||
- JavaScript/TypeScript files: `camelCase` for variables and functions, `PascalCase` for classes and components.
|
||||
- CSS/SCSS files: `kebab-case`.
|
||||
- **Module Organization:**
|
||||
- Split your application logic into separate modules for better maintainability and reusability.
|
||||
- Use ES modules (`import`/`export`) or CommonJS (`require`/`module.exports`) for modularization. Be consistent throughout the project.
|
||||
- **Component Architecture:**
|
||||
- Design reusable UI components for the renderer process.
|
||||
- Use a component-based framework (e.g., React, Vue, Angular) to manage UI complexity.
|
||||
- **Code Splitting:**
|
||||
- Implement code splitting to reduce the initial load time of your application.
|
||||
- Use dynamic imports (`import()`) to load modules on demand.
|
||||
- Consider using webpack or Parcel for bundling and code splitting.
|
||||
|
||||
- **Common Patterns and Anti-patterns**
|
||||
- **Design Patterns:**
|
||||
- **Model-View-Controller (MVC):** Organize application logic into models, views, and controllers to separate concerns.
|
||||
- **Observer Pattern:** Implement a publish-subscribe mechanism for communication between different parts of the application.
|
||||
- **Singleton Pattern:** Use singletons sparingly. If used, implement carefully to avoid unexpected side effects.
|
||||
- **Recommended Approaches:**
|
||||
- **Inter-Process Communication (IPC):** Use `ipcRenderer` and `ipcMain` for communication between the main and renderer processes. Sanitize all data passed via IPC.
|
||||
- **Native Modules:** Consider using native modules for performance-critical tasks or access to platform-specific APIs.
|
||||
- **Remote Module:** Avoid using the remote module, as it can introduce security vulnerabilities and performance issues. Use IPC instead.
|
||||
- **Anti-patterns:**
|
||||
- **Tight Coupling:** Avoid tightly coupling components or modules to make the code more flexible and testable.
|
||||
- **Global State:** Minimize the use of global state. Use state management libraries or techniques to manage application state effectively.
|
||||
- **Long-Running Tasks in the Renderer Process:** Move long-running tasks to the main process or use worker threads to prevent blocking the UI.
|
||||
- **State Management:**
|
||||
- For simple applications, use basic state management techniques (e.g., component state, context API).
|
||||
- For complex applications, consider using state management libraries like Redux, Zustand, or Vuex.
|
||||
- **Error Handling:**
|
||||
- Implement robust error handling mechanisms throughout your application.
|
||||
- Use try-catch blocks to handle exceptions and prevent crashes.
|
||||
- Log errors to a file or remote logging service for debugging.
|
||||
|
||||
- **Performance Considerations**
|
||||
- **Optimization Techniques:**
|
||||
- **Reduce Load on the Renderer Process:** Minimize the amount of work performed in the renderer process. Offload heavy tasks to the main process or worker threads.
|
||||
- **Hardware Acceleration:** Enable hardware acceleration to improve rendering performance.
|
||||
- **Minimize DOM Manipulations:** Reduce the number of DOM manipulations to improve UI responsiveness.
|
||||
- **Memory Management:**
|
||||
- **Garbage Collection:** Be mindful of memory leaks and optimize code to reduce memory consumption.
|
||||
- **Object Pools:** Use object pools to reuse objects and avoid unnecessary memory allocation.
|
||||
- **Rendering Optimization:**
|
||||
- **Virtual DOM:** Use a virtual DOM library (e.g., React, Vue) to optimize rendering performance.
|
||||
- **CSS Sprites:** Use CSS sprites to reduce the number of HTTP requests for images.
|
||||
- **Bundle Size Optimization:**
|
||||
- **Code Minification:** Minify JavaScript and CSS code to reduce bundle size.
|
||||
- **Tree Shaking:** Use tree shaking to remove unused code from the bundle.
|
||||
- **Lazy Loading:**
|
||||
- **Lazy Load Images:** Lazy load images to improve initial page load time.
|
||||
- **Lazy Load Modules:** Lazy load modules on demand to reduce initial bundle size.
|
||||
|
||||
- **Security Best Practices**
|
||||
- **Common Vulnerabilities:**
|
||||
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and escaping output.
|
||||
- **Remote Code Execution (RCE):** Avoid RCE vulnerabilities by validating input and preventing the execution of arbitrary code.
|
||||
- **Insecure Deserialization:** Prevent insecure deserialization vulnerabilities by validating serialized data.
|
||||
- **Input Validation:**
|
||||
- Validate all user input to prevent malicious data from being processed.
|
||||
- Use appropriate data types and formats to prevent type confusion attacks.
|
||||
- **Authentication and Authorization:**
|
||||
- Implement secure authentication and authorization mechanisms to protect sensitive data and resources.
|
||||
- Use strong passwords and multi-factor authentication.
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure storage mechanisms to protect sensitive data.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API communication.
|
||||
- Validate API responses to prevent data injection attacks.
|
||||
- **Enable Context Isolation:** Enable context isolation for the renderer process to prevent access to the main process's JavaScript context.
|
||||
- **Disable Node.js Integration:** Disable Node.js integration in the renderer process unless strictly necessary. If needed, only expose a limited API using contextBridge.
|
||||
- **Handle `new-window` events:** Validate and sanitize all URLs before allowing a new window to be opened from a renderer process.
|
||||
|
||||
- **Testing Approaches**
|
||||
- **Unit Testing:**
|
||||
- Write unit tests to verify the functionality of individual components or modules.
|
||||
- Use a testing framework like Jest or Mocha.
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to verify the interaction between different components or modules.
|
||||
- Use a testing framework like Cypress or Puppeteer.
|
||||
- **End-to-End Testing:**
|
||||
- Write end-to-end tests to verify the overall functionality of the application.
|
||||
- Use a testing framework like Cypress or Puppeteer.
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate files or directories based on functionality.
|
||||
- Use descriptive test names to clearly identify the purpose of each test.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing to isolate components or modules during testing.
|
||||
- Use a mocking library like Jest or Sinon.
|
||||
|
||||
- **Common Pitfalls and Gotchas**
|
||||
- **Frequent Mistakes:**
|
||||
- **Not Sanitizing User Input:** Failing to sanitize user input can lead to XSS vulnerabilities.
|
||||
- **Using the Remote Module:** The `remote` module provides direct access to main process functionality from the renderer, but bypassing IPC exposes security risks. Use `contextBridge` and IPC.
|
||||
- **Blocking the Main Process:** Performing long-running tasks in the main process can block the UI and make the application unresponsive.
|
||||
- **Edge Cases:**
|
||||
- **Handling Different Screen Resolutions:** Test your application on different screen resolutions to ensure proper UI rendering.
|
||||
- **Handling Different Operating Systems:** Test your application on different operating systems (Windows, macOS, Linux) to ensure compatibility.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of version-specific issues and compatibility concerns when upgrading Electron or its dependencies.
|
||||
- **Debugging Strategies:**
|
||||
- Use the Chrome DevTools to debug the renderer process.
|
||||
- Use the Electron DevTools to debug the main process.
|
||||
|
||||
- **Tooling and Environment**
|
||||
- **Recommended Development Tools:**
|
||||
- **Visual Studio Code:** A popular code editor with excellent support for Electron development.
|
||||
- **Electron Forge or Electron Builder:** Tools for packaging and distributing Electron applications.
|
||||
- **Chrome DevTools:** A powerful debugging tool for the renderer process.
|
||||
- **Build Configuration:**
|
||||
- Use a build system like webpack or Parcel to bundle your application code.
|
||||
- Configure the build system to optimize code for production.
|
||||
- **Linting and Formatting:**
|
||||
- Use a linter like ESLint to enforce code style and prevent errors.
|
||||
- Use a formatter like Prettier to automatically format code.
|
||||
- **Deployment Best Practices:**
|
||||
- Sign your application code to prevent tampering.
|
||||
- Distribute your application through a secure channel.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate your application with a CI/CD system to automate the build, test, and deployment process.
|
||||
@@ -0,0 +1,296 @@
|
||||
---
|
||||
description: This rule provides comprehensive guidelines for developing robust, secure, and performant Tauri applications. It covers code organization, security best practices, performance optimization, testing strategies, and common pitfalls to avoid.
|
||||
globs: **/*.(rs|js|ts|html|css|json|toml|md)
|
||||
---
|
||||
# Tauri Best Practices and Coding Standards
|
||||
|
||||
This document outlines best practices and coding standards for developing Tauri applications. Following these guidelines will help you create maintainable, secure, and performant applications.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure
|
||||
|
||||
Adopt a clear and consistent directory structure to improve maintainability and collaboration.
|
||||
|
||||
|
||||
my-tauri-app/
|
||||
├── .cargo/ # Cargo configuration
|
||||
├── .git/ # Git repository
|
||||
├── .gitignore # Git ignore file
|
||||
├── .rustfmt.toml # Rust code formatting configuration
|
||||
├── src-tauri/ # Rust backend source code
|
||||
│ ├── src/ # Rust source files
|
||||
│ │ ├── main.rs # Main application entry point
|
||||
│ │ ├── commands.rs # Custom commands
|
||||
│ │ ├── models.rs # Data models
|
||||
│ │ ├── utils.rs # Utility functions
|
||||
│ │ └── state.rs # Application State management
|
||||
│ ├── Cargo.toml # Rust project configuration
|
||||
│ ├── tauri.conf.json # Tauri application configuration
|
||||
│ └── icons/ # Application icons
|
||||
├── src/ # Web frontend source code
|
||||
│ ├── components/ # Reusable UI components
|
||||
│ │ ├── MyComponent.jsx # Example React component
|
||||
│ │ └── ...
|
||||
│ ├── pages/ # Application pages/routes
|
||||
│ │ ├── Home.jsx # Home page component
|
||||
│ │ └── ...
|
||||
│ ├── App.jsx # Main application component
|
||||
│ ├── index.css # Global styles
|
||||
│ ├── index.js # Entry point for web app
|
||||
│ ├── assets/ # Static assets (images, fonts, etc.)
|
||||
│ │ ├── logo.png # Application logo
|
||||
│ │ └── ...
|
||||
│ └── utils/ # Frontend utility functions
|
||||
├── static/ # Static resources (images, fonts, etc.) served directly
|
||||
├── README.md # Project documentation
|
||||
├── LICENSE # License file
|
||||
└── package.json # Node.js project configuration
|
||||
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
- **Rust files:** Use snake_case for file names (e.g., `my_module.rs`).
|
||||
- **JavaScript/TypeScript files:** Use PascalCase for component files (e.g., `MyComponent.jsx`) and camelCase for other files (e.g., `utils.js`).
|
||||
- **CSS files:** Use kebab-case (e.g., `main-styles.css`).
|
||||
- **HTML files:** Use kebab-case (e.g., `index.html`).
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
- Group related functionality into modules.
|
||||
- Use the `mod` keyword in Rust to define modules.
|
||||
- Create separate files for each module.
|
||||
- Use `pub` keyword to export items from modules.
|
||||
|
||||
rust
|
||||
// src-tauri/src/commands.rs
|
||||
|
||||
pub mod my_command {
|
||||
use tauri::{{command, State}};
|
||||
|
||||
#[command]
|
||||
pub fn greet(name: String) -> String {
|
||||
format!("Hello, {{}}! You've been greeted from Rust!", name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
- Adopt a component-based architecture for the frontend (e.g., using React, Vue, or Svelte).
|
||||
- Break down the UI into reusable components.
|
||||
- Follow a consistent component structure (e.g., separate files for component logic, styles, and tests).
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
- Implement code splitting to reduce the initial bundle size.
|
||||
- Use dynamic imports for lazy-loading modules and components.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to Tauri
|
||||
|
||||
- **Command Pattern:** Use Tauri commands to expose Rust functions to the frontend. This allows you to perform complex operations in Rust and communicate the results to the frontend.
|
||||
- **State Management:** Use a state management solution (e.g., Redux, Zustand, or React Context) to manage application state and ensure data consistency between the frontend and backend. Also use Tauri's `State` to manage state on the Rust side.
|
||||
- **Event System:** Use Tauri's event system for inter-process communication (IPC). The backend can emit events that the frontend listens for, enabling real-time updates and notifications.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
- **File System Access:** Use the Tauri API for file system access instead of directly using Node.js APIs. This ensures that your application respects the Tauri security model.
|
||||
- **External API Calls:** Perform external API calls in the Rust backend to protect API keys and sensitive data.
|
||||
- **Data Persistence:** Use a database or local storage for persistent data storage. Consider using an ORM like Diesel or SQLx for database access in Rust.
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
- **Over-reliance on JavaScript:** Offload complex logic to the Rust backend whenever possible to leverage Rust's performance and security features.
|
||||
- **Ignoring Security Policies:** Always configure and enforce strict Content Security Policies (CSPs) to prevent XSS attacks.
|
||||
- **Exposing Sensitive Data:** Avoid exposing sensitive data (e.g., API keys, database credentials) in the frontend code.
|
||||
- **Blocking the Main Thread:** Avoid long-running tasks on the main thread, both in Rust and JavaScript, to prevent the UI from freezing.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
- Choose a state management solution that fits your application's complexity.
|
||||
- Use immutable data structures to prevent accidental state mutations.
|
||||
- Centralize state management logic to improve maintainability.
|
||||
- Use Tauri's State management features to manage complex application states on the Rust side.
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
- Use Rust's `Result` type for error handling in the backend.
|
||||
- Provide informative error messages to the frontend.
|
||||
- Implement global error handling to catch unhandled exceptions.
|
||||
- Use appropriate logging to track errors and debug issues.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
- **Profiling:** Use profiling tools (e.g., Chrome DevTools, Rust's `perf` tool) to identify performance bottlenecks.
|
||||
- **Code Optimization:** Optimize Rust code for performance by using efficient algorithms, data structures, and memory management techniques.
|
||||
- **Webview Optimization:** Optimize frontend code for webview performance by reducing DOM manipulations, minimizing JavaScript execution time, and optimizing CSS styles.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
- Use Rust's ownership and borrowing system to prevent memory leaks and data races.
|
||||
- Avoid unnecessary allocations and deallocations.
|
||||
- Use smart pointers (e.g., `Box`, `Rc`, `Arc`) to manage memory ownership.
|
||||
|
||||
### 3.3 Rendering Optimization
|
||||
|
||||
- Use virtual DOM techniques to minimize DOM updates.
|
||||
- Optimize CSS selectors to improve rendering performance.
|
||||
- Use hardware acceleration for animations and transitions.
|
||||
|
||||
### 3.4 Bundle Size Optimization
|
||||
|
||||
- Use code splitting to reduce the initial bundle size.
|
||||
- Remove unused code and dependencies.
|
||||
- Optimize images and other assets.
|
||||
- Use a bundler (e.g., Webpack, Parcel, or Rollup) to optimize the bundle.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
- Use dynamic imports to lazy-load modules and components.
|
||||
- Load images and other assets only when they are visible.
|
||||
- Use a virtualized list to render large lists of data.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by enforcing strict Content Security Policies (CSPs) and sanitizing user inputs.
|
||||
- **Remote Code Execution (RCE):** Prevent RCE attacks by avoiding the use of `eval()` and other unsafe JavaScript functions. Isolate the webview context.
|
||||
- **SQL Injection:** Prevent SQL injection attacks by using parameterized queries or an ORM.
|
||||
- **Path Traversal:** Prevent path traversal attacks by validating user-provided file paths and using the Tauri API for file system access.
|
||||
- **Dependency Vulnerabilities:** Regularly update dependencies and use tools like `cargo audit` and `npm audit` to identify and fix vulnerabilities.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
- Validate all user inputs on both the frontend and backend.
|
||||
- Use appropriate data types and formats.
|
||||
- Sanitize inputs to remove potentially malicious characters.
|
||||
- Implement rate limiting to prevent brute-force attacks.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
- Use a secure authentication protocol (e.g., OAuth 2.0, JWT).
|
||||
- Store passwords securely using a strong hashing algorithm (e.g., bcrypt).
|
||||
- Implement authorization checks to ensure that users only have access to the resources they are authorized to access.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS for all network communication.
|
||||
- Store API keys and other secrets securely using environment variables or a dedicated secrets management solution.
|
||||
- Avoid storing sensitive data in the frontend code or in local storage.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
- Use the Tauri command pattern for secure communication between the frontend and backend.
|
||||
- Validate all data exchanged between the frontend and backend.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
- Use a secure communication protocol (e.g., TLS) for external API calls.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
- Write unit tests for all critical functions and modules.
|
||||
- Use a testing framework (e.g., `cargo test` for Rust, Jest or Mocha for JavaScript) to automate unit testing.
|
||||
- Aim for high code coverage.
|
||||
- Test edge cases and error conditions.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
- Write integration tests to verify the interaction between different modules and components.
|
||||
- Use a testing framework to automate integration testing.
|
||||
- Test the integration between the frontend and backend.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
- Write end-to-end tests to verify the entire application flow.
|
||||
- Use a testing framework (e.g., Cypress, Playwright) to automate end-to-end testing.
|
||||
- Test the application in a realistic environment.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
- Organize tests into separate directories for unit tests, integration tests, and end-to-end tests.
|
||||
- Follow a consistent naming convention for test files and functions.
|
||||
- Use test suites to group related tests.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
- Use mocking and stubbing to isolate units of code during testing.
|
||||
- Use a mocking framework (e.g., Mockall for Rust, Jest or Sinon.js for JavaScript) to create mocks and stubs.
|
||||
- Mock external dependencies and APIs.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
|
||||
- **Incorrectly Configuring CSP:** Not setting a restrictive enough content security policy.
|
||||
- **Misunderstanding Tauri's Security Model:** Assuming Node.js APIs are safe to use directly in the frontend.
|
||||
- **Ignoring Error Handling:** Not handling errors properly, leading to unexpected application behavior.
|
||||
- **Overcomplicating the Frontend:** Trying to do too much in the frontend, instead of leveraging the Rust backend.
|
||||
|
||||
### 6.2 Edge Cases to Be Aware Of
|
||||
|
||||
- **File System Permissions:** Handling file system permissions correctly on different operating systems.
|
||||
- **Webview Compatibility:** Ensuring compatibility with different webview versions.
|
||||
- **Application Update Process:** Handling application updates gracefully and securely.
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
|
||||
- Be aware of breaking changes in Tauri releases.
|
||||
- Consult the Tauri changelog for information about version-specific issues.
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
|
||||
- Test your application on different operating systems (Windows, macOS, Linux).
|
||||
- Test your application on different architectures (x86, x64, ARM).
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
|
||||
- Use the Tauri developer console for debugging frontend code.
|
||||
- Use Rust's debugging tools for debugging backend code.
|
||||
- Use logging to track application behavior.
|
||||
- Use a debugger to step through code and inspect variables.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
- **Rust:** Use the latest stable version of Rust.
|
||||
- **Node.js:** Use a recent version of Node.js.
|
||||
- **IDE:** Use a powerful IDE (e.g., Visual Studio Code, IntelliJ IDEA) with Rust and JavaScript/TypeScript support.
|
||||
- **Debugger:** Use a debugger (e.g., GDB, LLDB) for debugging Rust code.
|
||||
- **Web Inspector:** Use the web inspector (e.g., Chrome DevTools, Firefox Developer Tools) for debugging frontend code.
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
- Use the `tauri.conf.json` file to configure the build process.
|
||||
- Configure the application name, version, and other metadata.
|
||||
- Configure the build target and output directory.
|
||||
- Configure the security policies and permissions.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
- Use a linter (e.g., Clippy for Rust, ESLint for JavaScript) to enforce code style and identify potential issues.
|
||||
- Use a code formatter (e.g., Rustfmt for Rust, Prettier for JavaScript) to automatically format your code.
|
||||
- Configure your IDE to automatically run the linter and formatter on save.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
- Sign your application for the target platform.
|
||||
- Use a code signing certificate to verify the authenticity of your application.
|
||||
- Package your application for distribution using the appropriate tools (e.g., NSIS for Windows, DMG for macOS, DEB/RPM for Linux).
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
- Use a CI/CD system (e.g., GitHub Actions, GitLab CI, Jenkins) to automate the build, test, and deployment process.
|
||||
- Configure your CI/CD system to run the linter, formatter, and tests.
|
||||
- Configure your CI/CD system to automatically build and package your application for different platforms.
|
||||
- Automate the deployment process to reduce manual effort and errors.
|
||||
|
||||
By adhering to these best practices, you can develop Tauri applications that are secure, performant, and maintainable. Remember to stay updated with the latest Tauri documentation and community recommendations for continuous improvement.
|
||||
@@ -0,0 +1,200 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices and coding standards for Expo projects, covering code organization, performance, security, testing, and common pitfalls to ensure maintainable and high-quality applications.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
- **Code Organization and Structure**
|
||||
- **Directory Structure:**
|
||||
- Adopt a feature-based directory structure, grouping related files (components, hooks, styles, tests) within feature folders.
|
||||
- Examples:
|
||||
|
||||
src/
|
||||
├── components/
|
||||
│ ├── Button/
|
||||
│ │ ├── Button.tsx
|
||||
│ │ ├── Button.styles.ts
|
||||
│ │ └── Button.test.tsx
|
||||
│ └── ...
|
||||
├── screens/
|
||||
│ ├── Home/
|
||||
│ │ ├── HomeScreen.tsx
|
||||
│ │ ├── HomeScreen.styles.ts
|
||||
│ │ └── HomeScreen.test.tsx
|
||||
│ └── ...
|
||||
├── navigation/
|
||||
│ ├── AppNavigator.tsx
|
||||
│ └── ...
|
||||
├── services/
|
||||
│ ├── api.ts
|
||||
│ └── ...
|
||||
├── utils/
|
||||
│ ├── helpers.ts
|
||||
│ └── ...
|
||||
├── App.tsx
|
||||
└── index.tsx
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive and consistent names for files and directories.
|
||||
- Component files: `ComponentName.tsx` or `ComponentName.js`
|
||||
- Style files: `ComponentName.styles.ts` or `ComponentName.styles.js`
|
||||
- Hook files: `useHookName.ts` or `useHookName.js`
|
||||
- Test files: `ComponentName.test.tsx` or `ComponentName.test.js`
|
||||
- **Module Organization:**
|
||||
- Group related components, hooks, and utilities into modules.
|
||||
- Use `index.ts` (or `index.js`) files to export members from a module for easier importing.
|
||||
- Example:
|
||||
|
||||
// src/components/Button/index.ts
|
||||
export { default as Button } from './Button';
|
||||
|
||||
- **Component Architecture:**
|
||||
- Favor functional components with hooks for managing state and side effects.
|
||||
- Separate concerns by creating presentational (UI) and container (logic) components.
|
||||
- Use component composition to build complex UIs from smaller, reusable components.
|
||||
- **Code Splitting Strategies:**
|
||||
- Implement lazy loading for screens or components that are not immediately needed.
|
||||
- Utilize `React.lazy` and `Suspense` for dynamic imports.
|
||||
- Expo supports dynamic imports; leverage them to reduce initial bundle size.
|
||||
|
||||
- **Common Patterns and Anti-patterns**
|
||||
- **Design Patterns:**
|
||||
- **Higher-Order Components (HOCs):** Use cautiously; prefer hooks or render props for better composability.
|
||||
- **Render Props:** A pattern for sharing code between React components using a prop whose value is a function.
|
||||
- **Compound Components:** Create components that implicitly share state (e.g., Tabs and Tab).
|
||||
- **Recommended Approaches:**
|
||||
- Use Expo's APIs for accessing device features (camera, location, notifications) instead of relying on native modules directly where possible.
|
||||
- Leverage Expo's managed workflow for a smoother development experience.
|
||||
- **Anti-patterns:**
|
||||
- Directly manipulating the DOM (use React's state and props instead).
|
||||
- Writing complex logic directly within components (extract into hooks or utility functions).
|
||||
- Neglecting error handling and edge cases.
|
||||
- **State Management:**
|
||||
- Use React Context for simple state management.
|
||||
- Consider libraries like Zustand, Redux, or Jotai for more complex state management needs.
|
||||
- Leverage `useReducer` for managing complex state transitions.
|
||||
- **Error Handling:**
|
||||
- Implement try-catch blocks to handle potential errors.
|
||||
- Use error boundary components to catch errors during rendering.
|
||||
- Log errors using a centralized logging service (e.g., Sentry).
|
||||
|
||||
- **Performance Considerations**
|
||||
- **Optimization Techniques:**
|
||||
- Use `React.memo` to prevent unnecessary re-renders of components.
|
||||
- Implement `shouldComponentUpdate` (for class components) or `useMemo` and `useCallback` (for functional components) to optimize rendering.
|
||||
- Debounce or throttle event handlers to reduce the frequency of updates.
|
||||
- **Memory Management:**
|
||||
- Avoid creating large arrays or objects in component state if not necessary.
|
||||
- Clean up event listeners and timers when components unmount.
|
||||
- Release resources when they are no longer needed.
|
||||
- **Rendering Optimization:**
|
||||
- Virtualize long lists using `FlatList` or `SectionList` to improve scrolling performance.
|
||||
- Optimize image sizes and formats to reduce loading times.
|
||||
- Use the `useNativeDriver: true` prop in animations for better performance.
|
||||
- **Bundle Size Optimization:**
|
||||
- Use code splitting to reduce the initial bundle size.
|
||||
- Remove unused code and dependencies.
|
||||
- Optimize images and other assets.
|
||||
- **Lazy Loading:**
|
||||
- Implement lazy loading for images and other resources that are not immediately visible.
|
||||
- Use the `<Image>` component from `react-native` or `expo-image` with placeholder and loading indicators.
|
||||
|
||||
- **Security Best Practices**
|
||||
- **Common Vulnerabilities:**
|
||||
- Cross-Site Scripting (XSS) - Not typically a risk in React Native/Expo, but be mindful when rendering user-provided content via WebView.
|
||||
- Data injection - Protect against SQL or command injection if interacting with backend systems.
|
||||
- Insecure data storage - Never store sensitive information (API keys, credentials) directly in the app code.
|
||||
- **Input Validation:**
|
||||
- Validate user input on both the client and server sides.
|
||||
- Use appropriate data types and formats.
|
||||
- Sanitize user input to prevent injection attacks.
|
||||
- **Authentication and Authorization:**
|
||||
- Use secure authentication mechanisms (e.g., OAuth 2.0, JWT).
|
||||
- Implement proper authorization to restrict access to sensitive data and functionality.
|
||||
- Store authentication tokens securely (e.g., using Expo SecureStore).
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS for all API communication.
|
||||
- Avoid storing sensitive information in logs.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API requests.
|
||||
- Validate API responses.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
|
||||
- **Testing Approaches**
|
||||
- **Unit Testing:**
|
||||
- Write unit tests for individual components, hooks, and utility functions.
|
||||
- Use testing libraries like Jest and React Testing Library.
|
||||
- Mock dependencies to isolate units of code.
|
||||
- **Integration Testing:**
|
||||
- Test the interactions between multiple components or modules.
|
||||
- Use tools like Detox or Appium for end-to-end testing on real devices or emulators.
|
||||
- **End-to-end Testing:**
|
||||
- Simulate user interactions to test the entire application flow.
|
||||
- Use tools like Detox or Appium for end-to-end testing on real devices or emulators.
|
||||
- **Test Organization:**
|
||||
- Organize tests in a clear and maintainable structure.
|
||||
- Group tests by component or module.
|
||||
- Use descriptive names for test cases.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking to isolate units of code and simulate dependencies.
|
||||
- Use stubbing to replace complex or external dependencies with simplified versions.
|
||||
|
||||
- **Common Pitfalls and Gotchas**
|
||||
- **Frequent Mistakes:**
|
||||
- Forgetting to clean up event listeners or timers.
|
||||
- Mutating state directly instead of using `setState` or state update functions.
|
||||
- Over-rendering components due to unnecessary state updates.
|
||||
- **Edge Cases:**
|
||||
- Handling different screen sizes and orientations.
|
||||
- Dealing with slow network connections or API failures.
|
||||
- Managing application state during interruptions (e.g., phone calls).
|
||||
- **Version-specific Issues:**
|
||||
- Be aware of breaking changes in React Native and Expo SDK updates.
|
||||
- Test your application thoroughly after upgrading dependencies.
|
||||
- **Compatibility Concerns:**
|
||||
- Test your application on different devices and operating systems.
|
||||
- Use platform-specific code only when necessary.
|
||||
- **Debugging Strategies:**
|
||||
- Use the React Native debugger or Chrome DevTools for debugging.
|
||||
- Use console.log statements or debugging tools to inspect variables and application state.
|
||||
- Use error boundary components to catch and log errors.
|
||||
|
||||
- **Tooling and Environment**
|
||||
- **Recommended Tools:**
|
||||
- VS Code with Expo and ESLint extensions
|
||||
- Expo CLI for managing Expo projects.
|
||||
- React Native Debugger or Chrome DevTools for debugging.
|
||||
- **Build Configuration:**
|
||||
- Use environment variables to configure different build environments (development, staging, production).
|
||||
- Configure your build process to optimize assets and reduce bundle size.
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint with the Airbnb or Standard style guide.
|
||||
- Use Prettier to automatically format your code.
|
||||
- Configure your editor to automatically run ESLint and Prettier on save.
|
||||
- **Deployment:**
|
||||
- Use Expo Application Services (EAS) for building and deploying your application.
|
||||
- Follow Expo's deployment documentation for best practices.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate your application with a CI/CD pipeline (e.g., GitHub Actions, CircleCI).
|
||||
- Automate testing, linting, and deployment processes.
|
||||
|
||||
- **Expo Specific Recommendations**
|
||||
- **Use Expo Modules:** Prefer Expo modules for accessing native features over community libraries when available, as they are guaranteed to be compatible and well-maintained within the Expo ecosystem.
|
||||
- **EAS Build:** Use Expo Application Services (EAS) for building native binaries. This simplifies the build process and handles much of the complexity of native builds.
|
||||
- **Expo Updates:** Implement Expo Updates for over-the-air updates. This allows for quicker iteration and bug fixes without requiring users to download a new version from the app store.
|
||||
- **Managed Workflow:** Stick to the managed workflow whenever possible. It handles much of the native configuration and simplifies development.
|
||||
- **Expo SecureStore:** Use `expo-secure-store` to securely store sensitive data like API keys and tokens.
|
||||
- **Environment Variables:** Use `.env` files and `expo-constants` to manage environment-specific configurations.
|
||||
- **Asset Management:** Place assets (images, fonts) in the `assets` folder and use the `Image` and `Font` components to load them.
|
||||
|
||||
- **TypeScript Best Practices**
|
||||
- **Strict Mode:** Enable TypeScript's strict mode (`strict: true` in `tsconfig.json`) for enhanced type safety.
|
||||
- **Explicit Types:** Explicitly define types for function parameters, return values, and variables.
|
||||
- **Interfaces vs. Types:** Use interfaces for defining contract between objects, and types for defining data structures.
|
||||
- **Utility Types:** Leverage TypeScript's utility types (e.g., `Partial`, `Required`, `Readonly`, `Pick`, `Omit`) for more concise and maintainable code.
|
||||
- **Type Guards:** Use type guards to narrow down types within conditional blocks.
|
||||
- **Async/Await:** Use `async/await` for asynchronous operations to improve code readability and avoid callback hell.
|
||||
|
||||
- **Resources**
|
||||
- Expo Documentation: [https://docs.expo.dev/](https://docs.expo.dev/)
|
||||
- React Native Documentation: [https://reactnative.dev/](https://reactnative.dev/)
|
||||
- Expo JavaScript Style Guide: [https://github.com/expo/expo/blob/main/guides/Expo%20JavaScript%20Style%20Guide.md](https://github.com/expo/expo/blob/main/guides/Expo%20JavaScript%20Style%20Guide.md)
|
||||
@@ -0,0 +1,262 @@
|
||||
---
|
||||
description: Comprehensive guidelines and best practices for Flutter development, covering code organization, performance optimization, security, testing, and tooling.
|
||||
globs: **/*.dart
|
||||
---
|
||||
- Adhere to the official Flutter style guide. This forms the foundation for maintainable and consistent code.
|
||||
- Utilize the latest stable version of Flutter, keeping up-to-date with new features and security patches. Review Flutter's breaking changes and migration guides during updates.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- **1.1 Directory Structure Best Practices:**
|
||||
- **`lib/` (Source Code):**
|
||||
- Use a feature-based structure, grouping related components into modules.
|
||||
- Example:
|
||||
|
||||
lib/
|
||||
├── auth/
|
||||
│ ├── models/
|
||||
│ ├── providers/
|
||||
│ ├── screens/
|
||||
│ ├── services/
|
||||
│ ├── widgets/
|
||||
│ └── auth.dart
|
||||
├── home/
|
||||
│ ├── models/
|
||||
│ ├── screens/
|
||||
│ ├── widgets/
|
||||
│ └── home.dart
|
||||
├── common/
|
||||
│ ├── models/
|
||||
│ ├── widgets/
|
||||
│ └── utils/
|
||||
├── core/
|
||||
│ ├── services/
|
||||
│ ├── theme/
|
||||
│ └── utils/
|
||||
├── main.dart
|
||||
└── app.dart
|
||||
|
||||
- **`test/` (Tests):** Mirror the `lib/` structure for easy test discovery.
|
||||
- **`android/`, `ios/`, `web/`, `macos/`, `windows/`, `linux/` (Platform-Specific Code):** Contain platform-specific native code. Limit direct modification unless necessary; utilize Flutter's platform channels.
|
||||
- **`assets/` (Assets):** Store images, fonts, and other static resources. Organize subfolders by type (e.g., `images/`, `fonts/`, `data/`). Use `pubspec.yaml` to declare assets.
|
||||
|
||||
- **1.2 File Naming Conventions:**
|
||||
- Use `snake_case` for file names (e.g., `user_profile_screen.dart`).
|
||||
- For classes within a file, the file name typically reflects the main class it contains. Example: `user_profile_screen.dart` containing `UserProfileScreen`.
|
||||
- Exceptions: Grouping multiple related enums, typedefs, or small helper functions into a single file is acceptable if it improves clarity.
|
||||
|
||||
- **1.3 Module Organization:**
|
||||
- A module encapsulates a specific feature or functionality. Modules should have well-defined interfaces and minimize dependencies on other modules.
|
||||
- Implement a layered architecture within each module (e.g., UI, business logic, data access).
|
||||
- Consider using packages for large, independent features to promote reusability across projects.
|
||||
|
||||
- **1.4 Component Architecture:**
|
||||
- Favor a component-based architecture using Flutter widgets. Break down complex UIs into smaller, reusable widgets.
|
||||
- Separate presentation logic from business logic.
|
||||
- Widgets should be pure functions of their input data (state).
|
||||
- Follow the principles of Single Responsibility Principle (SRP) for widget design.
|
||||
|
||||
- **1.5 Code Splitting Strategies:**
|
||||
- **Deferred Loading:** Load features on demand to reduce initial app size.
|
||||
- **Route-Based Splitting:** Split code based on app routes.
|
||||
- **Feature-Based Splitting:** Split code based on features.
|
||||
- Use the `dart:ui` library's `loadFontFromList` or `ImageProvider.loadBuffer` to load font or image resources dynamically.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
- **2.1 Design Patterns Specific to Flutter:**
|
||||
- **BLoC (Business Logic Component):** Separates business logic from the UI, making the code more testable and maintainable.
|
||||
- **Provider:** Simple dependency injection and state management solution.
|
||||
- **Riverpod:** An improved version of Provider with compile-time safety.
|
||||
- **GetX:** A microframework that provides state management, dependency injection, and route management.
|
||||
- **MVVM (Model-View-ViewModel):** Another pattern for separating concerns. Often used with reactive programming.
|
||||
- **Redux/Flux:** For predictable state management, especially in complex applications.
|
||||
- **InheritedWidget:** Implicit dependency injection for theming and configuration.
|
||||
|
||||
- **2.2 Recommended Approaches for Common Tasks:**
|
||||
- **State Management:** Choose a state management solution that fits the complexity of the app.
|
||||
- **Networking:** Use the `http` package or `dio` for making API requests.
|
||||
- **Asynchronous Operations:** Use `async/await` for handling asynchronous operations.
|
||||
- **Data Persistence:** Use `shared_preferences` for simple data storage or SQLite (using packages like `sqflite`) or NoSQL databases (using packages like `hive` or `isar`) for structured data.
|
||||
- **Navigation:** Use `go_router` or `auto_route` for type-safe navigation.
|
||||
- **Form Handling:** Use `Form` widget with `TextFormField` and validators.
|
||||
|
||||
- **2.3 Anti-patterns and Code Smells to Avoid:**
|
||||
- **Massive Widgets:** Widgets with too much logic or UI code. Break them down into smaller, reusable components.
|
||||
- **Logic in Widgets:** Avoid putting business logic directly inside widgets.
|
||||
- **Deeply Nested Widgets:** Can lead to performance issues and difficult-to-read code. Simplify the widget tree.
|
||||
- **Unmanaged State:** Forgetting to dispose of resources like `StreamSubscription` or `AnimationController` leading to memory leaks.
|
||||
- **Hardcoded Values:** Avoid hardcoding values like colors, sizes, and strings in the code. Use constants or theme data.
|
||||
- **Ignoring Errors:** Not handling exceptions properly can lead to unexpected crashes. Use `try-catch` blocks and logging.
|
||||
|
||||
- **2.4 State Management Best Practices:**
|
||||
- Choose a state management solution that fits the complexity of the app.
|
||||
- Keep the state as close to where it is needed as possible. Avoid global state for everything.
|
||||
- Use immutable data structures to prevent unexpected state changes.
|
||||
- Separate state from UI components to improve testability.
|
||||
- Manage side effects properly.
|
||||
- Consider reactive programming with streams for complex state transitions.
|
||||
|
||||
- **2.5 Error Handling Patterns:**
|
||||
- Use `try-catch` blocks to handle exceptions.
|
||||
- Implement custom error classes for specific error scenarios.
|
||||
- Log errors to a file or remote service for debugging.
|
||||
- Show user-friendly error messages.
|
||||
- Use `ErrorWidget` to display custom error screens.
|
||||
- Handle asynchronous errors using `Future.catchError` or `Stream.handleError`.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
- **3.1 Optimization Techniques:**
|
||||
- **Avoid Unnecessary Widget Rebuilds:** Use `const` constructors for immutable widgets, `shouldRebuild` method in `StatefulWidget`, and `ValueKey` for widgets that change position in a list.
|
||||
- **Minimize `setState` Calls:** Use state management solutions to optimize state updates.
|
||||
- **Use `ListView.builder` or `GridView.builder`:** For large lists or grids, build widgets lazily.
|
||||
- **Use `RepaintBoundary`:** Isolate parts of the UI that don't need to be repainted often.
|
||||
- **Use `Opacity` and `Clip` Sparingly:** These operations can be expensive.
|
||||
- **Use `Transform` carefully:** transforms can break batching and cause additional draw calls.
|
||||
|
||||
- **3.2 Memory Management:**
|
||||
- Dispose of resources like `StreamSubscription`, `AnimationController`, and `TextEditingController` in the `dispose` method.
|
||||
- Avoid creating unnecessary objects.
|
||||
- Use the `dart:developer` package's memory profiling tools to identify memory leaks.
|
||||
- Minimize the use of global variables and static fields.
|
||||
|
||||
- **3.3 Rendering Optimization:**
|
||||
- Use the Flutter Performance Overlay to identify performance bottlenecks.
|
||||
- Reduce the complexity of the widget tree.
|
||||
- Optimize image loading and caching.
|
||||
- Avoid using custom paint operations unless necessary.
|
||||
|
||||
- **3.4 Bundle Size Optimization:**
|
||||
- Use `flutter build apk --split-per-abi` or `flutter build appbundle` to split the APK/AAB by ABI (Application Binary Interface).
|
||||
- Remove unused assets and code.
|
||||
- Compress images.
|
||||
- Use code obfuscation and minification.
|
||||
- Use deferred loading for infrequently used features.
|
||||
|
||||
- **3.5 Lazy Loading Strategies:**
|
||||
- **Image Lazy Loading:** Load images only when they are visible on the screen.
|
||||
- **Data Lazy Loading:** Load data in chunks as the user scrolls.
|
||||
- Use the `VisibilityDetector` package to detect when a widget becomes visible.
|
||||
- Use pagination or infinite scrolling for large datasets.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
- **4.1 Common Vulnerabilities and How to Prevent Them:**
|
||||
- **Data Injection:** Sanitize user input to prevent SQL injection, XSS, and other injection attacks.
|
||||
- **Sensitive Data Storage:** Avoid storing sensitive data in plain text. Use encryption and secure storage mechanisms.
|
||||
- **Insecure API Communication:** Use HTTPS for all API communication.
|
||||
- **Code Tampering:** Use code obfuscation to make it harder to reverse engineer the app.
|
||||
- **Man-in-the-Middle Attacks:** Implement certificate pinning to prevent MITM attacks.
|
||||
|
||||
- **4.2 Input Validation:**
|
||||
- Validate all user input on both the client and server sides.
|
||||
- Use regular expressions or custom validation logic to enforce data constraints.
|
||||
- Encode data properly before displaying it in the UI.
|
||||
|
||||
- **4.3 Authentication and Authorization Patterns:**
|
||||
- Use secure authentication protocols like OAuth 2.0 or OpenID Connect.
|
||||
- Implement multi-factor authentication (MFA) for added security.
|
||||
- Use role-based access control (RBAC) to restrict access to sensitive data and functionality.
|
||||
- Store authentication tokens securely.
|
||||
|
||||
- **4.4 Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure storage mechanisms like the Keychain (iOS) or Keystore (Android).
|
||||
- Follow the principle of least privilege when granting access to data.
|
||||
|
||||
- **4.5 Secure API Communication:**
|
||||
- Use HTTPS for all API communication.
|
||||
- Implement proper authentication and authorization.
|
||||
- Validate API responses.
|
||||
- Rate limit API requests to prevent abuse.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
- **5.1 Unit Testing Strategies:**
|
||||
- Test individual functions, classes, and widgets in isolation.
|
||||
- Use mock objects to isolate the code under test from its dependencies.
|
||||
- Write tests for all critical business logic.
|
||||
|
||||
- **5.2 Integration Testing:**
|
||||
- Test the interaction between different parts of the app.
|
||||
- Test the integration with external services like APIs and databases.
|
||||
|
||||
- **5.3 End-to-End Testing:**
|
||||
- Test the entire app from start to finish.
|
||||
- Simulate user interactions to ensure that the app works as expected.
|
||||
|
||||
- **5.4 Test Organization:**
|
||||
- Create a `test/` directory that mirrors the `lib/` directory structure.
|
||||
- Use descriptive test names.
|
||||
- Keep tests small and focused.
|
||||
|
||||
- **5.5 Mocking and Stubbing:**
|
||||
- Use mocking frameworks like `mockito` to create mock objects.
|
||||
- Use stubbing to replace external dependencies with predefined values.
|
||||
- Avoid over-mocking, as it can make tests less effective.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
- **6.1 Frequent Mistakes Developers Make:**
|
||||
- Not disposing of resources.
|
||||
- Ignoring errors.
|
||||
- Hardcoding values.
|
||||
- Using `setState` excessively.
|
||||
- Creating massive widgets.
|
||||
- Not validating user input.
|
||||
- Over-complicating the state management.
|
||||
|
||||
- **6.2 Edge Cases to Be Aware Of:**
|
||||
- Network connectivity issues.
|
||||
- Device orientation changes.
|
||||
- Background app state.
|
||||
- Low memory conditions.
|
||||
- Localization and internationalization.
|
||||
|
||||
- **6.3 Version-Specific Issues:**
|
||||
- Be aware of breaking changes in new Flutter releases.
|
||||
- Test the app on different Flutter versions to ensure compatibility.
|
||||
- Use version constraints in `pubspec.yaml` to specify the required Flutter version.
|
||||
|
||||
- **6.4 Compatibility Concerns:**
|
||||
- Test the app on different devices and operating systems.
|
||||
- Consider accessibility for users with disabilities.
|
||||
- Follow platform-specific guidelines for UI and functionality.
|
||||
|
||||
- **6.5 Debugging Strategies:**
|
||||
- Use the Flutter DevTools for debugging and profiling.
|
||||
- Use logging to track down errors.
|
||||
- Use breakpoints to step through the code.
|
||||
- Use the Flutter Inspector to inspect the widget tree.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
- **7.1 Recommended Development Tools:**
|
||||
- Visual Studio Code or Android Studio.
|
||||
- Flutter DevTools.
|
||||
- Android Emulator or iOS Simulator.
|
||||
- Git for version control.
|
||||
|
||||
- **7.2 Build Configuration:**
|
||||
- Use `flutter build` to build the app for different platforms.
|
||||
- Configure build settings in `pubspec.yaml`.
|
||||
- Use different build configurations for development, staging, and production.
|
||||
|
||||
- **7.3 Linting and Formatting:**
|
||||
- Use `flutter_lints` package for linting.
|
||||
- Use `dart format` or Prettier for code formatting.
|
||||
- Configure the IDE to automatically format the code on save.
|
||||
|
||||
- **7.4 Deployment Best Practices:**
|
||||
- Follow the deployment guidelines for each platform.
|
||||
- Use code signing to ensure the authenticity of the app.
|
||||
- Use version control to manage releases.
|
||||
- Monitor the app for crashes and errors after deployment.
|
||||
|
||||
- **7.5 CI/CD Integration:**
|
||||
- Use a CI/CD tool like GitHub Actions, GitLab CI, or Jenkins to automate the build, test, and deployment process.
|
||||
- Configure the CI/CD pipeline to run linting, formatting, and testing.
|
||||
- Automate the release process to the app stores.
|
||||
|
||||
This document provides comprehensive guidelines and best practices for Flutter development. Following these guidelines will help you write maintainable, performant, and secure Flutter apps.
|
||||
@@ -0,0 +1,217 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices and coding standards for React Native development, covering code organization, performance, security, testing, and common pitfalls.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
- Use TypeScript for type safety and improved code maintainability.
|
||||
- Prefer functional components with hooks over class components for simplicity and reusability.
|
||||
- Maintain a clear and consistent project structure for scalability and maintainability.
|
||||
|
||||
## 1. Code Organization and Structure:
|
||||
|
||||
- **Directory Structure:**
|
||||
- Adopt a feature-based or component-based structure. For example:
|
||||
|
||||
src/
|
||||
├── components/
|
||||
│ ├── Button/
|
||||
│ │ ├── Button.tsx
|
||||
│ │ ├── Button.styles.ts
|
||||
│ │ ├── Button.test.tsx
|
||||
│ ├── Input/
|
||||
│ └── ...
|
||||
├── screens/
|
||||
│ ├── Home/
|
||||
│ │ ├── HomeScreen.tsx
|
||||
│ │ ├── HomeScreen.styles.ts
|
||||
│ │ ├── HomeScreen.test.tsx
|
||||
│ ├── Profile/
|
||||
│ └── ...
|
||||
├── navigation/
|
||||
├── services/
|
||||
├── utils/
|
||||
├── types/
|
||||
└── App.tsx
|
||||
|
||||
- Separate concerns into distinct directories (e.g., components, screens, navigation, services, utils, types).
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive names for files and components (e.g., `HomeScreen.tsx`, `useUserData.ts`).
|
||||
- Follow a consistent naming convention (e.g., PascalCase for components, camelCase for functions and variables).
|
||||
- Use `.styles.ts` for style files and `.test.tsx` for test files to keep components readable and organized.
|
||||
|
||||
- **Module Organization:**
|
||||
- Group related components and modules into logical units.
|
||||
- Use absolute imports and module aliases to avoid long relative paths (e.g., `@components/Button` instead of `../../../components/Button`).
|
||||
- Configure module aliases in `tsconfig.json` or `jsconfig.json`.
|
||||
|
||||
- **Component Architecture:**
|
||||
- Favor small, reusable components with a single responsibility (Single Responsibility Principle).
|
||||
- Use composition over inheritance to create complex components.
|
||||
- Consider using a UI library like React Native Paper or NativeBase for pre-built components.
|
||||
|
||||
- **Code Splitting Strategies:**
|
||||
- Implement lazy loading for screens or components that are not immediately needed.
|
||||
- Use `React.lazy` and `Suspense` to load components on demand.
|
||||
- Utilize dynamic imports for conditional loading of modules.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns:
|
||||
|
||||
- **Design Patterns:**
|
||||
- **Higher-Order Components (HOCs):** Use HOCs for cross-cutting concerns like authentication or logging.
|
||||
- **Render Props:** Use render props to share code between React components.
|
||||
- **Hooks:** Use custom hooks to encapsulate logic and stateful behavior.
|
||||
|
||||
- **Recommended Approaches:**
|
||||
- **State Management:**
|
||||
- Use React Context for simple state management.
|
||||
- Use Redux, Zustand, or Jotai for complex state management.
|
||||
- Consider using Recoil for fine-grained state management.
|
||||
- **API Calls:**
|
||||
- Use `axios` or `fetch` for making API requests.
|
||||
- Create a service layer to handle API calls and data transformations.
|
||||
- **Navigation:**
|
||||
- Use React Navigation for managing app navigation.
|
||||
- Define navigation stacks and routes in a separate module.
|
||||
|
||||
- **Anti-patterns and Code Smells:**
|
||||
- **Long Component Files:** Break down large components into smaller, more manageable pieces.
|
||||
- **Deeply Nested Components:** Avoid excessive nesting, which can impact performance.
|
||||
- **Mutating State Directly:** Always use `setState` or a state management library to update state.
|
||||
- **Unnecessary Re-renders:** Optimize components to prevent unnecessary re-renders.
|
||||
- **Global Styles:** Avoid using global styles, as they can lead to conflicts and make it difficult to maintain the application.
|
||||
|
||||
- **State Management Best Practices:**
|
||||
- Choose a state management solution that fits the complexity of your application.
|
||||
- Keep state minimal and derive values when possible.
|
||||
- Use selectors to access state and memoize computed values.
|
||||
|
||||
- **Error Handling Patterns:**
|
||||
- Use `try...catch` blocks to handle errors gracefully.
|
||||
- Implement a global error handler to catch unhandled exceptions.
|
||||
- Log errors to a remote monitoring service.
|
||||
|
||||
## 3. Performance Considerations:
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Memoization:** Use `React.memo` to memoize components and prevent unnecessary re-renders.
|
||||
- **Pure Components:** Extend `React.PureComponent` for components that only depend on props.
|
||||
- **Debouncing and Throttling:** Use debouncing and throttling to limit the frequency of function calls.
|
||||
- **Virtualization:** Use `FlatList` or `SectionList` for rendering large lists of data.
|
||||
|
||||
- **Memory Management:**
|
||||
- Avoid memory leaks by properly cleaning up event listeners and timers.
|
||||
- Use `useCallback` and `useMemo` to prevent creating new functions and objects on every render.
|
||||
|
||||
- **Rendering Optimization:**
|
||||
- Minimize the number of re-renders by optimizing component updates.
|
||||
- Use `shouldComponentUpdate` (for class components) or `React.memo` to control re-renders.
|
||||
- Avoid using inline styles, as they are re-created on every render.
|
||||
|
||||
- **Bundle Size Optimization:**
|
||||
- Use code splitting to reduce the initial bundle size.
|
||||
- Remove unused code and dependencies.
|
||||
- Use a bundler like Metro or Webpack with tree shaking enabled.
|
||||
- Compress images and other assets.
|
||||
|
||||
- **Lazy Loading Strategies:**
|
||||
- Implement lazy loading for images and other assets using `React.lazy` and `Suspense`.
|
||||
- Use dynamic imports to load modules on demand.
|
||||
|
||||
## 4. Security Best Practices:
|
||||
|
||||
- **Common Vulnerabilities:**
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks.
|
||||
- **SQL Injection:** Use parameterized queries to prevent SQL injection attacks.
|
||||
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection tokens.
|
||||
- **Man-in-the-Middle (MITM) Attacks:** Use HTTPS to encrypt communication.
|
||||
|
||||
- **Input Validation:**
|
||||
- Validate user input on both the client and server sides.
|
||||
- Use regular expressions or validation libraries to enforce input constraints.
|
||||
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use a secure authentication protocol like OAuth 2.0 or JWT.
|
||||
- Implement role-based access control (RBAC) to restrict access to sensitive resources.
|
||||
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure storage mechanisms for storing API keys and other secrets.
|
||||
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API communication.
|
||||
- Implement API rate limiting to prevent abuse.
|
||||
- Validate API responses to prevent data injection attacks.
|
||||
|
||||
## 5. Testing Approaches:
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Write unit tests for individual components and modules.
|
||||
- Use a testing framework like Jest or Mocha.
|
||||
- Mock dependencies to isolate the component being tested.
|
||||
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to verify the interaction between components and modules.
|
||||
- Test the integration with external APIs and services.
|
||||
|
||||
- **End-to-End Testing:**
|
||||
- Write end-to-end tests to verify the entire application flow.
|
||||
- Use a testing framework like Detox or Appium.
|
||||
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories based on component or module.
|
||||
- Use descriptive names for test files and test cases.
|
||||
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing to isolate components and control their behavior during testing.
|
||||
- Use a mocking library like Jest or Sinon.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas:
|
||||
|
||||
- **Frequent Mistakes:**
|
||||
- **Directly Mutating State:** Always use `setState` or a state management library to update state.
|
||||
- **Ignoring Platform Differences:** Test your application on both iOS and Android devices.
|
||||
- **Over-Optimizing:** Optimize only when necessary, as premature optimization can lead to complex code.
|
||||
- **Not Using a Debugger:** Utilize the React Native debugger for efficient debugging.
|
||||
|
||||
- **Edge Cases:**
|
||||
- **Handling Device Orientation Changes:** Implement logic to handle device orientation changes gracefully.
|
||||
- **Handling Network Connectivity Issues:** Implement error handling for network connectivity issues.
|
||||
- **Handling Different Screen Sizes and Densities:** Design your UI to adapt to different screen sizes and densities.
|
||||
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of breaking changes in React Native and its dependencies.
|
||||
- Test your application with different versions of React Native.
|
||||
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that your application is compatible with the target operating systems and devices.
|
||||
- Use polyfills to support older browsers and devices.
|
||||
|
||||
- **Debugging Strategies:**
|
||||
- Use the React Native debugger to inspect the component tree and state.
|
||||
- Use the console to log messages and debug code.
|
||||
- Use a remote debugging tool to debug on a physical device.
|
||||
|
||||
## 7. Tooling and Environment:
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **VS Code:** Use VS Code with the React Native Tools extension for debugging and code completion.
|
||||
- **React Native CLI:** Use the React Native CLI for creating and managing React Native projects.
|
||||
- **Expo CLI:** Use the Expo CLI for developing and testing React Native applications without native code.
|
||||
- **Android Studio:** Use Android Studio for building and debugging Android applications.
|
||||
- **Xcode:** Use Xcode for building and debugging iOS applications.
|
||||
|
||||
- **Build Configuration:**
|
||||
- Use a build system like Gradle (Android) or CocoaPods (iOS) to manage dependencies.
|
||||
- Configure build variants for different environments (e.g., development, staging, production).
|
||||
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint and Prettier to enforce code style and catch potential errors.
|
||||
- Configure ESLint and Prettier to automatically format code on save.
|
||||
|
||||
- **Deployment Best Practices:**
|
||||
- Use a continuous integration and continuous deployment (CI/CD) pipeline to automate the deployment process.
|
||||
- Use a service like App Center or Bitrise for building and deploying React Native applications.
|
||||
|
||||
- **CI/CD Integration:**
|
||||
- Integrate your code repository with a CI/CD service like GitHub Actions or CircleCI.
|
||||
- Configure the CI/CD pipeline to run tests and build the application on every commit.
|
||||
Reference in New Issue
Block a user