使用 Tauri 框架构建跨平台应用
Tauri 是一个基于 Rust 的轻量级框架,可替代 Electron,用于构建高性能、低资源占用的桌面应用。其核心优势在于利用系统原生 WebView 而非捆绑 Chromium,显著减小应用体积。
安装 Tauri 需要先配置 Rust 环境:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
创建新项目:
npm create tauri-app@latest
项目结构包括 src-tauri
(Rust 后端)和前端代码目录(如 React/Vue)。
配置前端与 Rust 交互
Tauri 允许前端调用 Rust 函数实现高性能操作。在 src-tauri/src/main.rs
中定义命令:
#[tauri::command]
fn greet(name: &str) -> String {format!("Hello, {}!", name)
}fn main() {tauri::Builder::default().invoke_handler(tauri::generate_handler![greet]).run(tauri::generate_context!()).expect("error while running app");
}
前端调用示例(JavaScript):
import { invoke } from '@tauri-apps/api';
invoke('greet', { name: 'World' }).then(console.log);
打包与平台适配
Tauri 支持 Windows、macOS 和 Linux。生成安装包:
npm run tauri build
配置文件 tauri.conf.json
可自定义应用图标、权限等:
{"build": {"distDir": "../dist","devPath": "http://localhost:3000"},"tauri": {"bundle": {"targets": ["msi", "app", "deb"]}}
}
集成系统原生功能
通过 Tauri 的 API 访问文件系统、通知等:
use tauri::api::dialog::message;
#[tauri::command]
fn show_alert(title: &str, content: &str) {message(title, content);
}
前端调用:
invoke('show_alert', { title: '提示', content: '操作成功' });
性能优化技巧
- 减小体积:禁用未使用的 Tauri 模块(如
tauri::updater
)。 - 代码分割:动态加载前端资源。
- Rust 优化:使用
#[inline]
或lto = true
(在Cargo.toml
中)。
[profile.release]
lto = true
codegen-units = 1