文章目录
一、为什么是 Tauri?------ Electron 的"轻量继任者"
Electron 虽然广泛使用,但问题明显:体积大、内存高、Node 主进程存在安全风险。
Tauri 以 Rust 为底层,WebView 为前端,优势包括:
- 应用体积仅 5~10MB;
- 启动快,内存占用低;
- 系统安全控制更强。
二、Tauri + Vue3 / React 项目初始化
bash
npm create vite@latest tauri-demo --template vue-ts
cd tauri-demo
npm install
npx tauri init
npm run tauri dev
结构如下:
tauri-demo/
├─ src/ # 前端逻辑
├─ src-tauri/ # Rust 后端逻辑
│ ├─ src/main.rs
│ └─ tauri.conf.json
三、Rust 模块:文件读取与缓存
src/api/file.ts
ts
import { invoke } from "@tauri-apps/api";
export async function readFileContent(path: string): Promise<string> {
return await invoke("read_file_content", { path });
}
export async function writeCacheFile(key: string, data: string) {
return await invoke("write_cache_file", { key, data });
}
src-tauri/src/main.rs
rust
use std::{fs, path::PathBuf};
use tauri::command;
#[command]
fn read_file_content(path: String) -> Result<String, String> {
fs::read_to_string(path).map_err(|e| e.to_string())
}
#[command]
fn write_cache_file(key: String, data: String) -> Result<String, String> {
let dir = tauri::api::path::cache_dir().ok_or("无法获取缓存目录")?;
let path = dir.join(format!("{}.cache", key));
fs::write(&path, data).map_err(|e| e.to_string())?;
Ok(path.display().to_string())
}
四、Vue 前端调用示例
src/App.vue
vue
<template>
<div class="app">
<h1>📁 文件内容读取器</h1>
<input v-model="path" placeholder="文件路径" />
<button @click="loadFile">读取</button>
<pre>{{ content }}</pre>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { readFileContent, writeCacheFile } from "./api/file";
const path = ref("");
const content = ref("");
async function loadFile() {
const text = await readFileContent(path.value);
content.value = text;
await writeCacheFile("last_read", text);
}
</script>
五、构建与发布
bash
npm run tauri build
生成可执行文件:
src-tauri/target/release/tauri-demo.exe
支持 Windows / macOS / Linux 打包签名与自动更新。
六、安全性 + 性能对比
| 对比维度 | Electron | Tauri |
|---|---|---|
| 核心语言 | Node.js + Chromium | Rust + 系统 WebView |
| 体积 | ~150MB | 5~10MB |
| 内存占用 | 高 | 低 |
| 启动速度 | 秒级 | <500ms |
| 系统安全 | 弱 | 强 |
Tauri 借助 Rust 在性能和安全上实现系统级提升。
七、Rust 后端扩展:网络请求
Cargo.toml
toml
[dependencies]
reqwest = { version = "0.11", features = ["blocking", "json"] }
serde = { version = "1.0", features = ["derive"] }
src-tauri/src/main.rs
rust
#[command]
fn download_file(url: String) -> Result<String, String> {
let resp = reqwest::blocking::get(&url)
.map_err(|e| e.to_string())?;
let body = resp.text().map_err(|e| e.to_string())?;
let dir = tauri::api::path::download_dir()
.ok_or("无法获取下载目录")?;
let path = dir.join("downloaded.txt");
std::fs::write(&path, body).map_err(|e| e.to_string())?;
Ok(path.display().to_string())
}
八、生态扩展
常用插件:
tauri-plugin-store持久化存储;tauri-plugin-notification桌面通知;tauri-plugin-sql本地数据库;tauri-plugin-updater热更新。
九、结语
Electron 开启了"桌面前端时代";
而 Tauri + Rust,开启了"系统级前端时代"。
Rust 让前端开发者拥有系统级能力,
构建体积小、性能高、安全强的桌面应用。