mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+249
-224
@@ -1,296 +1,321 @@
|
||||
---
|
||||
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)
|
||||
description: This guide provides definitive, actionable best practices for writing robust, performant, and secure Rust backend code in Tauri applications, focusing on modern patterns and common pitfalls.
|
||||
globs: **/*.rs
|
||||
---
|
||||
# Tauri Best Practices and Coding Standards
|
||||
# Tauri Best Practices (Rust Backend)
|
||||
|
||||
This document outlines best practices and coding standards for developing Tauri applications. Following these guidelines will help you create maintainable, secure, and performant applications.
|
||||
Tauri applications thrive on a lean, secure Rust backend. This guide outlines the essential patterns and anti-patterns for writing high-quality Rust code that integrates seamlessly with your frontend.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure
|
||||
Organize your Rust code by feature, not by file type. Keep related structs, enums, and their `impl` blocks together within a module. Leverage Rust's module system for clear separation of concerns and encapsulation.
|
||||
|
||||
Adopt a clear and consistent directory structure to improve maintainability and collaboration.
|
||||
**✅ GOOD: Feature-based Modules**
|
||||
|
||||
```rust
|
||||
// src-tauri/src/main.rs
|
||||
mod user; // Defines the 'user' module
|
||||
|
||||
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)
|
||||
}
|
||||
fn main() {
|
||||
// ...
|
||||
}
|
||||
|
||||
// src-tauri/src/user/mod.rs
|
||||
pub mod manager; // Exposes user::manager
|
||||
|
||||
// src-tauri/src/user/manager.rs
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
### 1.4 Component Architecture
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct User {
|
||||
pub id: u32,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
- 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).
|
||||
impl User {
|
||||
pub fn new(id: u32, name: String) -> Self {
|
||||
Self { id, name }
|
||||
}
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
pub fn greet(&self) -> String {
|
||||
format!("Hello, {}!", self.name)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Implement code splitting to reduce the initial bundle size.
|
||||
- Use dynamic imports for lazy-loading modules and components.
|
||||
**❌ BAD: Separating Types and Implementations**
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
```rust
|
||||
// src-tauri/src/types.rs (AVOID)
|
||||
pub struct User { /* ... */ }
|
||||
|
||||
### 2.1 Design Patterns Specific to Tauri
|
||||
// src-tauri/src/user_impls.rs (AVOID)
|
||||
impl User { /* ... */ }
|
||||
```
|
||||
|
||||
- **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.
|
||||
> **Action**: Always run `cargo fmt` and `cargo clippy` to enforce standard Rust style and catch common errors.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
## 2. Tauri Command Fundamentals
|
||||
|
||||
- **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.
|
||||
Tauri commands are the bridge between your frontend and Rust backend. Keep them focused, asynchronous, and delegate complex logic.
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
**✅ GOOD: Lean, Async Commands**
|
||||
|
||||
- **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.
|
||||
```rust
|
||||
// src-tauri/src/main.rs
|
||||
#[tauri::command]
|
||||
async fn greet(name: String) -> Result<String, String> {
|
||||
// Delegate complex logic to a dedicated service/manager
|
||||
let greeting = user::manager::User::new(0, name).greet();
|
||||
Ok(greeting)
|
||||
}
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.invoke_handler(tauri::generate_handler![greet])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
- 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.
|
||||
**❌ BAD: Blocking or Overly Complex Commands**
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
```rust
|
||||
// src-tauri/src/main.rs (AVOID)
|
||||
#[tauri::command]
|
||||
fn process_large_file_sync(path: String) -> Result<String, String> {
|
||||
// This blocks the main thread, making the UI unresponsive
|
||||
std::thread::sleep(std::time::Duration::from_secs(5));
|
||||
Ok(format!("Processed {}", path))
|
||||
}
|
||||
```
|
||||
|
||||
- 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. Manage Global State with `tauri::State`
|
||||
|
||||
## 3. Performance Considerations
|
||||
For shared, mutable application state, `tauri::State` is the definitive solution. Wrap your state in `Arc<Mutex<T>>` or `Arc<RwLock<T>>` for thread-safe access.
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
**✅ GOOD: Thread-Safe Global State**
|
||||
|
||||
- **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.
|
||||
```rust
|
||||
// src-tauri/src/main.rs
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
### 3.2 Memory Management
|
||||
struct AppState {
|
||||
counter: u32,
|
||||
}
|
||||
|
||||
- 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.
|
||||
#[tauri::command]
|
||||
fn increment_counter(state: tauri::State<'_, Arc<Mutex<AppState>>>) -> Result<u32, String> {
|
||||
let mut app_state = state.lock().map_err(|e| format!("State lock error: {}", e))?;
|
||||
app_state.counter += 1;
|
||||
Ok(app_state.counter)
|
||||
}
|
||||
|
||||
### 3.3 Rendering Optimization
|
||||
fn main() {
|
||||
let app_state = Arc::new(Mutex::new(AppState { counter: 0 }));
|
||||
tauri::Builder::default()
|
||||
.manage(app_state) // Register the state
|
||||
.invoke_handler(tauri::generate_handler![increment_counter])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
- Use virtual DOM techniques to minimize DOM updates.
|
||||
- Optimize CSS selectors to improve rendering performance.
|
||||
- Use hardware acceleration for animations and transitions.
|
||||
**❌ BAD: Unmanaged Global Statics**
|
||||
|
||||
### 3.4 Bundle Size Optimization
|
||||
```rust
|
||||
// src-tauri/src/main.rs (AVOID)
|
||||
static mut GLOBAL_COUNTER: u32 = 0; // NOT thread-safe, prone to data races
|
||||
#[tauri::command]
|
||||
fn get_global_counter() -> u32 {
|
||||
unsafe { GLOBAL_COUNTER } // Unsafe code, difficult to reason about
|
||||
}
|
||||
```
|
||||
|
||||
- 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.
|
||||
## 4. Robust Error Handling
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
Use `thiserror` or `anyhow` for structured error handling. Always return `Result<T, E>` from commands, where `E` is a serializable error type. This allows the frontend to display meaningful error messages.
|
||||
|
||||
- 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.
|
||||
**✅ GOOD: Custom, Serializable Errors**
|
||||
|
||||
## 4. Security Best Practices
|
||||
```rust
|
||||
// src-tauri/src/error.rs
|
||||
use thiserror::Error;
|
||||
use serde::Serialize;
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
#[derive(Debug, Error, Serialize)]
|
||||
pub enum AppError {
|
||||
#[error("Resource not found: {0}")]
|
||||
NotFound(String),
|
||||
#[error("Database operation failed: {0}")]
|
||||
Database(String),
|
||||
#[error("Internal server error: {0}")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
- **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.
|
||||
impl From<std::io::Error> for AppError {
|
||||
fn from(err: std::io::Error) -> Self {
|
||||
AppError::Internal(format!("IO error: {}", err))
|
||||
}
|
||||
}
|
||||
|
||||
### 4.2 Input Validation
|
||||
// src-tauri/src/main.rs
|
||||
use tauri::async_runtime::spawn_blocking;
|
||||
use crate::error::AppError; // Assuming error.rs is in src
|
||||
|
||||
- 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.
|
||||
#[tauri::command]
|
||||
async fn read_config_file(path: String) -> Result<String, AppError> {
|
||||
// Use spawn_blocking for potentially blocking I/O
|
||||
spawn_blocking(move || {
|
||||
std::fs::read_to_string(&path).map_err(|e| AppError::from(e))
|
||||
}).await.map_err(|e| AppError::Internal(format!("Blocking task failed: {}", e)))?
|
||||
}
|
||||
```
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
**❌ BAD: Generic Error Strings or Panics**
|
||||
|
||||
- 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.
|
||||
```rust
|
||||
// src-tauri/src/main.rs (AVOID)
|
||||
#[tauri::command]
|
||||
fn divide(a: u32, b: u32) -> Result<u32, String> {
|
||||
if b == 0 {
|
||||
return Err("Cannot divide by zero".to_string()); // Generic string
|
||||
}
|
||||
Ok(a / b)
|
||||
}
|
||||
#[tauri::command]
|
||||
fn dangerous_operation() {
|
||||
panic!("Something went wrong!"); // Crashes the backend
|
||||
}
|
||||
```
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
## 5. Performance Considerations
|
||||
|
||||
- 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.
|
||||
Tauri's multi-process model means the Rust core can run heavy tasks without freezing the UI. Leverage `async/await` and `spawn_blocking` for optimal responsiveness.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
**✅ GOOD: Offload Blocking Tasks**
|
||||
|
||||
- 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.
|
||||
```rust
|
||||
// src-tauri/src/main.rs
|
||||
use tauri::async_runtime::spawn_blocking;
|
||||
|
||||
## 5. Testing Approaches
|
||||
#[tauri::command]
|
||||
async fn perform_heavy_computation() -> Result<u64, String> {
|
||||
let result = spawn_blocking(|| {
|
||||
// Simulate a CPU-bound blocking task
|
||||
let mut sum = 0;
|
||||
for i in 0..1_000_000; {
|
||||
sum += i;
|
||||
}
|
||||
sum
|
||||
}).await.map_err(|e| e.to_string())?;
|
||||
Ok(result)
|
||||
}
|
||||
```
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
**❌ BAD: Blocking the Async Runtime**
|
||||
|
||||
- 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.
|
||||
```rust
|
||||
// src-tauri/src/main.rs (AVOID)
|
||||
#[tauri::command]
|
||||
async fn sync_network_call() -> Result<String, String> {
|
||||
// This blocks the async runtime, impacting other async tasks
|
||||
let response = reqwest::blocking::get("http://example.com")
|
||||
.map_err(|e| e.to_string())?
|
||||
.text()
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(response)
|
||||
}
|
||||
```
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
### Security: Principle of Least Privilege
|
||||
|
||||
- **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.
|
||||
**Opinion**: Explicitly define capabilities in `src-tauri/tauri.conf.json`. Never grant wildcard access (`*`) unless absolutely necessary for specific, audited plugins.
|
||||
|
||||
### 6.2 Edge Cases to Be Aware Of
|
||||
**✅ GOOD: Granular Capabilities (`src-tauri/tauri.conf.json`)**
|
||||
|
||||
- **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.
|
||||
```json
|
||||
{
|
||||
"tauri": {
|
||||
"allowlist": {
|
||||
"fs": {
|
||||
"readFile": true,
|
||||
"writeFile": true,
|
||||
"scope": ["$APPCONFIG/*", "$APPDATA/*"]
|
||||
},
|
||||
"shell": {
|
||||
"open": true
|
||||
}
|
||||
},
|
||||
"security": {
|
||||
"csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline';"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
**❌ BAD: Overly Permissive Capabilities (`src-tauri/tauri.conf.json`)**
|
||||
|
||||
- Be aware of breaking changes in Tauri releases.
|
||||
- Consult the Tauri changelog for information about version-specific issues.
|
||||
```json
|
||||
{
|
||||
"tauri": {
|
||||
"allowlist": {
|
||||
"all": true // Grants access to ALL APIs, highly insecure
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
### Frontend vs. Backend Logic
|
||||
|
||||
- Test your application on different operating systems (Windows, macOS, Linux).
|
||||
- Test your application on different architectures (x86, x64, ARM).
|
||||
**Opinion**: Keep sensitive data and business logic exclusively in the Rust backend. The frontend (WebView) should only handle UI presentation and user interaction.
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
**✅ GOOD: Rust for Sensitive Logic**
|
||||
|
||||
- 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.
|
||||
```rust
|
||||
// src-tauri/src/main.rs
|
||||
#[tauri::command]
|
||||
async fn process_payment(amount: f64, token: String) -> Result<String, AppError> {
|
||||
// Payment processing logic, interacts with secure APIs
|
||||
// ...
|
||||
Ok("Payment successful".into())
|
||||
}
|
||||
```
|
||||
|
||||
## 7. Tooling and Environment
|
||||
**❌ BAD: Handling Secrets in Frontend JavaScript**
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
```javascript
|
||||
// src/main.js (AVOID)
|
||||
async function sendPayment() {
|
||||
const secretApiKey = "YOUR_HARDCODED_API_KEY"; // EXPOSED!
|
||||
// ... send payment directly from frontend
|
||||
}
|
||||
```
|
||||
|
||||
- **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. Testing Approaches
|
||||
|
||||
### 7.2 Build Configuration
|
||||
Unit test your Rust modules independently. For commands, consider integration tests that simulate frontend calls.
|
||||
|
||||
- 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.
|
||||
**✅ GOOD: Unit Testing Rust Logic**
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
```rust
|
||||
// src-tauri/src/user/manager.rs
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
- 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.
|
||||
#[test]
|
||||
fn test_user_greeting() {
|
||||
let user = User::new(1, "Alice".into());
|
||||
assert_eq!(user.greet(), "Hello, Alice!");
|
||||
}
|
||||
|
||||
### 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.
|
||||
#[test]
|
||||
fn test_user_id() {
|
||||
let user = User::new(42, "Bob".into());
|
||||
assert_eq!(user.id, 42);
|
||||
}
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user