tauri-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTauri 最佳实践
Tauri Best Practices
功能概述
Overview
Tauri 跨平台桌面应用开发最佳实践。
💡 创建新项目请使用 tauri-create 技能。
Best practices for cross-platform desktop application development with Tauri.
💡 Use the tauri-create skill to create new projects.
核心原则
Core Principles
1. 优先使用 JS 插件,避免编写 Rust 代码
1. Prioritize JS Plugins, Avoid Writing Rust Code
为什么:
- 减少编译时间
- 降低 Rust 学习成本
- Tauri 2.x 插件生态已完善
常用官方插件:
| 插件 | 功能 | 安装命令 |
|---|---|---|
| 打开 URL、执行命令 | |
| 文件系统访问 | |
| 文件对话框 | |
| 系统通知 | |
| 剪贴板操作 | |
| HTTP 请求 | |
| 数据持久化 | |
| 窗口状态记忆 | |
📌 完整插件列表:https://v2.tauri.app/zh-cn/plugin/
注意事项:
- 插件安装限制:一次只能添加一个插件
pnpm tauri add
bash
pnpm tauri add clipboard-manager
pnpm tauri add window-state- 插件导入方式:分全部导入和解构导入
typescript
// 导入全部方法
import * as Clipboard from '@tauri-apps/plugin-clipboard-manager'
// 然后使用
await Clipboard.writeText(text)
// 解构导入
import { writeText, readText } from '@tauri-apps/plugin-clipboard-manager'Why:
- Reduce compilation time
- Lower Rust learning curve
- Tauri 2.x plugin ecosystem is mature
Common Official Plugins:
| Plugin | Function | Installation Command |
|---|---|---|
| Open URLs, execute commands | |
| File system access | |
| File dialogs | |
| System notifications | |
| Clipboard operations | |
| HTTP requests | |
| Data persistence | |
| Window state persistence | |
📌 Complete Plugin List: https://v2.tauri.app/zh-cn/plugin/
Notes:
- Plugin Installation Limit: can only add one plugin at a time
pnpm tauri add
bash
pnpm tauri add clipboard-manager
pnpm tauri add window-state- Plugin Import Methods: Full import and destructuring import
typescript
// Import all methods
import * as Clipboard from '@tauri-apps/plugin-clipboard-manager'
// Then use
await Clipboard.writeText(text)
// Destructuring import
import { writeText, readText } from '@tauri-apps/plugin-clipboard-manager'2. 前端封装 API 层,支持浏览器开发
2. Frontend API Layer Encapsulation, Support Browser Development
架构设计:
src/
├── api/
│ └── clipboard.ts # 封装好的剪贴板 API
├── lib/
│ └── platform.ts # 环境检测
└── main.ts实现示例:
typescript
// src/lib/platform.ts
export const isTauri = () => '__TAURI__' in window
// src/api/clipboard.ts
import * as Clipboard from '@tauri-apps/plugin-clipboard-manager'
import { isTauri } from '@/lib/platform'
export async function writeText(text: string): Promise<void> {
if (isTauri()) {
await Clipboard.writeText(text)
} else {
await navigator.clipboard.writeText(text)
}
}
export async function readText(): Promise<string> {
if (isTauri()) {
return await Clipboard.readText()
} else {
return await navigator.clipboard.readText()
}
}
// 使用
import { writeText, readText } from '@/api/clipboard'
await writeText('Hello')Web 不支持的处理方式:
typescript
// 方式 1:返回默认值/Mock 数据
export async function getAppVersion(): Promise<string> {
if (isTauri()) {
return await app.getVersion()
}
return '0.0.0-browser' // 开发时使用模拟值
}
// 方式 2:抛出明确错误
export async function readFile(path: string): Promise<string> {
if (isTauri()) {
return await fs.readTextFile(path)
}
throw new Error('File API 仅在桌面端可用')
}
// 方式 3:提供降级方案
export async function saveData(key: string, value: string): Promise<void> {
if (isTauri()) {
await fs.writeTextFile(`data/${key}.txt`, value)
} else {
localStorage.setItem(key, value) // 浏览器降级到 localStorage
}
}优势:
- 单文件维护,只需关注一个实现
- 浏览器开发,热更新快
- 统一接口,易于使用
Architecture Design:
src/
├── api/
│ └── clipboard.ts # Encapsulated clipboard API
├── lib/
│ └── platform.ts # Environment detection
└── main.tsImplementation Example:
typescript
// src/lib/platform.ts
export const isTauri = () => '__TAURI__' in window
// src/api/clipboard.ts
import * as Clipboard from '@tauri-apps/plugin-clipboard-manager'
import { isTauri } from '@/lib/platform'
export async function writeText(text: string): Promise<void> {
if (isTauri()) {
await Clipboard.writeText(text)
} else {
await navigator.clipboard.writeText(text)
}
}
export async function readText(): Promise<string> {
if (isTauri()) {
return await Clipboard.readText()
} else {
return await navigator.clipboard.readText()
}
}
// Usage
import { writeText, readText } from '@/api/clipboard'
await writeText('Hello')Handling Web-Unsupported Features:
typescript
// Method 1: Return default/mock data
export async function getAppVersion(): Promise<string> {
if (isTauri()) {
return await app.getVersion()
}
return '0.0.0-browser' // Use mock value during development
}
// Method 2: Throw explicit error
export async function readFile(path: string): Promise<string> {
if (isTauri()) {
return await fs.readTextFile(path)
}
throw new Error('File API is only available on desktop')
}
// Method 3: Provide fallback solution
export async function saveData(key: string, value: string): Promise<void> {
if (isTauri()) {
await fs.writeTextFile(`data/${key}.txt`, value)
} else {
localStorage.setItem(key, value) // Fallback to localStorage in browser
}
}Advantages:
- Single file maintenance, only focus on one implementation
- Browser development with fast hot reload
- Unified interface, easy to use
使用示例
Usage Examples
场景 1:审查现有项目
Scenario 1: Review Existing Project
用户输入:"帮我审查一下这个 Tauri 项目的代码"
审查要点:
- 检查是否优先使用了官方插件而非自定义 Rust 代码
- 检查是否有前端 API 层封装(如 目录)
src/api/ - 检查是否支持浏览器开发模式
- 检查插件导入方式是否合理
- 提出改进建议
User Input: "Help me review the code of this Tauri project"
Review Points:
- Check if official plugins are prioritized over custom Rust code
- Check if there is a frontend API layer encapsulation (e.g., directory)
src/api/ - Check if browser development mode is supported
- Check if plugin import methods are reasonable
- Propose improvement suggestions
场景 2:实现新功能
Scenario 2: Implement New Feature
用户输入:"我需要实现剪贴板功能"
推荐方案:
- 使用官方 插件
@tauri-apps/plugin-clipboard-manager - 在 中封装 API
src/api/clipboard.ts - 添加环境检测,支持浏览器降级
- 业务代码直接调用封装后的 API
User Input: "I need to implement clipboard functionality"
Recommended Solution:
- Use the official plugin
@tauri-apps/plugin-clipboard-manager - Encapsulate API in
src/api/clipboard.ts - Add environment detection to support browser fallback
- Call the encapsulated API directly in business code
场景 3:性能优化建议
Scenario 3: Performance Optimization Suggestions
用户输入:"编译时间太长了,有什么优化建议?"
优化方向:
- 减少自定义 Rust 代码,优先使用 JS 插件
- 检查 中不必要的依赖
Cargo.toml - 使用开发模式的增量编译
- 考虑使用前端封装层在浏览器中开发
User Input: "Compilation time is too long, what optimization suggestions do you have?"
Optimization Directions:
- Reduce custom Rust code, prioritize JS plugins
- Check for unnecessary dependencies in
Cargo.toml - Use incremental compilation in development mode
- Consider using frontend encapsulation layer for development in browser
场景 4:架构设计咨询
Scenario 4: Architecture Design Consultation
用户输入:"我要设计一个 Tauri 应用的架构"
架构建议:
- 前端优先:大部分功能用前端技术栈实现
- API 层封装:在 中统一封装 Tauri API
src/api/ - 环境抽象:通过 检测实现双环境支持
isTauri() - 插件优先:优先使用官方插件,避免编写 Rust 代码
User Input: "I want to design the architecture of a Tauri application"
Architecture Suggestions:
- Frontend-first: Implement most features with frontend tech stack
- API layer encapsulation: Unify Tauri API encapsulation in
src/api/ - Environment abstraction: Achieve dual-environment support via detection
isTauri() - Plugin-first: Prioritize official plugins, avoid writing Rust code
常见问题
Frequently Asked Questions
问题:什么时候需要编写 Rust 代码?
Q: When do I need to write Rust code?
判断标准:
- 现有插件无法满足需求 → 考虑自定义 Rust 代码
- 需要操作系统级别的特殊功能 → 可能需要 Rust
- 性能敏感的操作(如大量数据处理) → 可以考虑 Rust
优先级:官方插件 > 社区插件 > 自定义 Rust 代码
Judgment Criteria:
- Existing plugins cannot meet requirements → Consider custom Rust code
- Need OS-level special functions → May require Rust
- Performance-sensitive operations (e.g., large data processing) → Can consider Rust
Priority: Official Plugins > Community Plugins > Custom Rust Code
问题:如何处理浏览器不支持的功能?
Q: How to handle features not supported by browsers?
三种处理方式(详见上文"前端封装 API 层"章节):
- 返回默认值/Mock 数据(适合开发阶段)
- 抛出明确错误(适合必须功能)
- 提供降级方案(如 localStorage 替代文件系统)
Three Handling Methods (see "Frontend API Layer Encapsulation" section above):
- Return default/mock data (suitable for development stage)
- Throw explicit error (suitable for mandatory features)
- Provide fallback solution (e.g., localStorage instead of file system)
问题:插件一次安装失败怎么办?
Q: What if plugin installation fails once?
注意事项:
- 一次只能添加一个插件
pnpm tauri add - 需要多次执行安装命令
- 安装后需要在 中配置权限
src-tauri/capabilities/default.json
Notes:
- can only add one plugin at a time
pnpm tauri add - Need to execute installation commands multiple times
- After installation, configure permissions in
src-tauri/capabilities/default.json
问题:如何测试 Tauri 应用?
Q: How to test Tauri applications?
推荐流程:
- 使用 进行纯前端开发(快速热更新)
pnpm dev - 核心功能完成后使用 测试桌面端集成
pnpm tauri dev - 构建前使用 在目标平台测试
pnpm tauri build
Recommended Process:
- Use for pure frontend development (fast hot reload)
pnpm dev - Test desktop integration with after core features are completed
pnpm tauri dev - Test on target platform with before packaging
pnpm tauri build
注意事项
Notes
- Tauri 版本:此技能基于 Tauri 2.x,不适用于 1.x
- 插件权限:安装插件后需要在 中配置权限
src-tauri/capabilities/default.json - 双环境开发:推荐在浏览器中开发,桌面端测试
- 性能考虑:减少 Rust 代码可显著缩短编译时间
- 安全建议:谨慎使用 插件执行命令,避免命令注入风险
shell - 项目关联:创建新项目建议使用 tauri-create 技能
- Tauri Version: This skill is based on Tauri 2.x, not applicable to 1.x
- Plugin Permissions: Configure permissions in after installing plugins
src-tauri/capabilities/default.json - Dual-Environment Development: Recommended to develop in browser and test on desktop
- Performance Consideration: Reducing Rust code can significantly shorten compilation time
- Security Suggestion: Be cautious when using plugin to execute commands, avoid command injection risks
shell - Project Association: Recommend using tauri-create skill to create new projects