Tauri 开发助手
任务目标
- 本 Skill 用于:辅助开发者使用 Tauri 构建跨平台桌面应用
- 能力包含:项目初始化、架构设计、前后端通信、系统 API 集成、打包发布、调试优化
- 触发条件:用户需要创建 Tauri 应用、集成系统能力、解决 Tauri 开发问题或优化现有 Tauri 项目
前置准备
- 依赖环境:Rust (最新版)、Node.js (18+)、Rust 相关工具链
- 非标准准备:
- Windows: Visual Studio Build Tools
- macOS: Xcode Command Line Tools
- Linux: GCC/Make、libsoup-devel、webkit2gtk4.0-devel
操作步骤
一、项目初始化
1.1 选择脚手架工具
根据前端技术栈选择初始化方式:
| 前端框架 | 推荐命令 | 特点 |
|---------|---------|------|
| Vanilla (无框架) | npm create tauri-app@latest | 最轻量,完全自主控制 |
| React | 同上,选择 React 模板 | 生态丰富 |
| Vue | 同上,选择 Vue 模板 | 响应式简单易用 |
| Svelte | 同上,选择 Svelte 模板 | 体积小,性能好 |
| Solid | 同上,选择 Solid 模板 | 性能接近原生 |
1.2 初始化命令
# 交互式初始化(推荐)
npm create tauri-app@latest my-app
# 非交互式(一次性指定)
npm create tauri-app@latest my-app -- --template react-ts --manager npm
1.3 初始化后的目录结构
my-app/
├── src/ # 前端源码
│ ├── main.ts # 前端入口
│ ├── App.tsx # 根组件
│ └── styles/ # 样式文件
├── src-tauri/ # Rust 后端
│ ├── src/
│ │ ├── main.rs # 入口
│ │ ├── lib.rs # 库入口
│ │ └── commands/ # Tauri 命令(按需创建)
│ ├── Cargo.toml # Rust 依赖
│ ├── tauri.conf.json # Tauri 配置
│ ├── capabilities/ # 权限配置(v2)
│ └── build.rs # 构建配置
├── package.json
└── vite.config.ts # Vite 配置
二、核心配置
2.1 tauri.conf.json 关键配置
{
"productName": "MyApp",
"version": "1.0.0",
"identifier": "com.myapp.desktop",
"build": {
"devtools": true
},
"app": {
"windows": [
{
"title": "MyApp",
"width": 1200,
"height": 800,
"resizable": true,
"center": true
}
],
"security": {
"csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}
2.2 权限配置 (v2 API)
Tauri v2 采用 capabilities 机制管理权限:
// src-tauri/capabilities/main.json
{
"$schema": "https://schema.tauri.app/v2/capabilities",
"identifier": "main-capability",
"description": "Main window capability",
"windows": ["main"],
"permissions": [
"core:default",
"core:window:allow-close",
"core:window:allow-minimize",
"core:window:allow-maximize",
"core:window:allow-unmaximize",
"core:window:allow-set-title",
"fs:default",
"fs:allow-read-text-file",
"fs:allow-write-text-file",
"dialog:default",
"dialog:allow-open",
"dialog:allow-save",
"clipboard-manager:default",
"notification:default",
"notification:allow-request-permission",
"notification:allow-notify"
]
}
三、前后端通信
3.1 Rust 端定义命令
// src-tauri/src/lib.rs 或 commands/mod.rs
use tauri::command;
#[command]
pub fn greet(name: &str) -> Result<String, String> {
if name.is_empty() {
return Err("Name cannot be empty".into());
}
Ok(format!("Hello, {}!", name))
}
#[command]
pub async fn fetch_data(url: String) -> Result<String, String> {
// 异步命令示例
let response = reqwest::get(&url)
.await
.map_err(|e| e.to_string())?;
response.text().await.map_err(|e| e.to_string())
}
3.2 前端调用 Rust 命令
// npm install @tauri-apps/api
import { invoke } from '@tauri-apps/api/core';
// 调用同步命令
async function greetUser() {
try {
const result = await invoke<string>('greet', { name: 'World' });
console.log(result); // "Hello, World!"
} catch (e) {
console.error('Error:', e);
}
}
// 调用异步命令
async function getData() {
const data = await invoke<string>('fetch_data', { url: 'https://api.example.com' });
console.log(data);
}
3.3 事件系统 (Frontend <-> Backend)
Rust 发送事件:
use tauri::{AppHandle, Emitter};
#[command]
pub fn start_process(app: AppHandle) {
std::thread::spawn(move || {
for i in 0..10 {
app.emit("progress", i).unwrap();
std::thread::sleep(std::time::Duration::from_millis(500));
}
app.emit("complete", "Done!").unwrap();
});
}
前端监听事件:
import { listen } from '@tauri-apps/api/event';
// 监听进度事件
const unlisten = await listen<number>('progress', (event) => {
console.log(`Progress: ${event.payload}%`);
});
// 监听完成事件
await listen('complete', (event) => {
console.log(event.payload);
unlisten(); // 取消监听
});
四、系统集成
4.1 文件系统操作
添加依赖 (Cargo.toml):
[dependencies]
tauri-plugin-fs = "2"
tauri-plugin-dialog = "2"
tauri-plugin-shell = "2"
前端使用:
import { readTextFile, writeTextFile } from '@tauri-apps/plugin-fs';
import { open, save } from '@tauri-apps/plugin-dialog';
import { open as shellOpen } from '@tauri-apps/plugin-shell';
// 读取文件
const content = await readTextFile('./config.json');
// 写入文件
await writeTextFile('./output.txt', 'Hello World');
// 打开文件对话框
const file = await open({
multiple: false,
filters: [{ name: 'Text', extensions: ['txt', 'md'] }]
});
// 保存文件对话框
const path = await save({
filters: [{ name: 'JSON', extensions: ['json'] }],
defaultPath: 'untitled.json'
});
// 打开外部链接
await shellOpen('https://tauri.app');
4.2 剪贴板
// Cargo.toml 添加
tauri-plugin-clipboard-manager = "2"
import { writeText, readText } from '@tauri-apps/plugin-clipboard-manager';
await writeText('Hello from Tauri!');
const text = await readText();
4.3 系统通知
tauri-plugin-notification = "2"
import { isPermissionGranted, requestPermission, sendNotification } from '@tauri-apps/plugin-notification';
let permissionGranted = await isPermissionGranted();
if (!permissionGranted) {
const permission = await requestPermission();
permissionGranted = permission === 'granted';
}
if (permissionGranted) {
sendNotification({ title: 'Tauri App', body: 'Hello!' });
}
五、开发与调试
5.1 开发模式
# 启动开发服务器
npm run tauri dev
# 或分别启动
npm run dev # 前端热重载
npm run tauri dev -- --no-watch # 仅 Rust 编译
5.2 Rust 调试
# 详细日志
RUST_LOG=debug npm run tauri dev
# 附加调试器
# VS Code: .vscode/launch.json
{
"name": "Tauri Debug",
"type": "cppvsdbg",
"request": "attach",
"program": "${workspaceFolder}/src-tauri/target/debug/my_app.exe",
"processId": "${command:pickProcess}"
}
5.3 前端调试
- Windows/Linux: 右键 → 检查元素,或使用 DevTools
- macOS: 右键 → 检查元素
- 开启 DevTools: 在
tauri.conf.json中设置"build": { "devtools": true }
六、打包发布
6.1 正式构建
npm run tauri build
6.2 多平台交叉编译
安装交叉编译工具链:
# Windows -> Linux
rustup target add x86_64-unknown-linux-gnu
# 需要 mingw-w64
# macOS Universal Binary
rustup target add aarch64-apple-darwin x86_64-apple-darwin
配置 .cargo/config.toml:
[target.x86_64-pc-windows-msvc]
linker = "..."
[build]
target = "x86_64-pc-windows-msvc"
6.3 发布配置
// tauri.conf.json
{
"bundle": {
"publisher": "Your Name",
"copyright": "Copyright 2024",
"shortDescription": "A Tauri app",
"longDescription": "Detailed description...",
"category": "Utility",
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": ""
}
}
}
使用示例
示例 1: 创建基础 Tauri 项目
- 场景/输入:用户想要创建一个带文件系统访问功能的桌面应用
- 预期产出:完整可运行的项目,包含前后端通信和文件操作
- 关键要点:
- 选择合适的前端框架(推荐 React 或 Vue)
- 添加 fs/dialog 插件
- 配置 capabilities 权限
- 在 Rust 中定义命令处理复杂逻辑
示例 2: 实现前后端通信
- 场景/输入:需要在前端调用 Rust 处理敏感数据或执行系统级操作
- 预期产出:安全的前后端通信桥梁
- 关键要点:
- Rust 命令返回 Result,使用 ? 操作符传播错误
- 前端使用 try-catch 处理错误
- 异步命令使用 async/await
- 大数据量使用事件系统分段传输
示例 3: 打包发布应用
- 场景/输入:开发完成,准备发布
- 预期产出:各平台的安装包
- 关键要点:
- 配置正确的 app identifier
- 准备各尺寸应用图标
- 配置代码签名(生产环境)
- 使用 GitHub Actions 实现 CI/CD
资源索引
- 参考:见 references/architecture.md(何时读取:设计项目架构、确定目录结构)
- 参考:见 references/system-integration.md(何时读取:集成系统能力如文件系统、剪贴板、通知)
- 参考:见 references/debugging.md(何时读取:调试应用、排查问题、性能优化)
- 参考:见 references/packaging.md(何时读取:打包应用、配置 CI/CD、发布上线)
注意事项
- 权限最小化:仅申请应用必需权限,避免过度授权
- 错误处理:前后端通信必须正确处理错误,避免 panic
- 安全实践:敏感数据不在前端暴露,Rust 端处理加密等操作
- 性能考虑:避免在前端线程中执行耗时操作,使用异步命令
- 版本匹配:前端插件版本需与 Tauri 版本兼容
Scan to join WeChat group