understanding-tauri-architecture by dchuk/claude-code-tauri-skills
npx skills add https://github.com/dchuk/claude-code-tauri-skills --skill understanding-tauri-architectureTauri 是一个多语言工具包,用于构建桌面应用程序,它将 Rust 后端与在原生 WebView 中渲染的 HTML/CSS/JavaScript 相结合。本文档涵盖了基本的架构概念。
+------------------------------------------------------------------+
| TAURI 应用程序 |
+------------------------------------------------------------------+
| |
| +---------------------------+ +---------------------------+ |
| | 前端 (Shell) | | 后端 (Core) | |
| |---------------------------| |---------------------------| |
| | | | | |
| | HTML / CSS / JavaScript | | Rust 代码 | |
| | (或任何 Web 框架) | | (tauri crate + app) | |
| | | | | |
| | - React, Vue, Svelte, | | - 系统访问 | |
| | Solid, 等 | | - 文件操作 | |
| | - 标准 Web API | | - 原生功能 | |
| | - Tauri JS API | | - 插件系统 | |
| | | | | |
| +-------------+-------------+ +-------------+-------------+ |
| | | |
| | IPC (消息传递) | |
| +<------------------------------->+ |
| | 命令与事件 | |
| |
| +------------------------------------------------------------+ |
| | WEBVIEW (TAO + WRY) | |
| |------------------------------------------------------------| |
| | - 平台原生 WebView (非捆绑式) | |
| | - Windows: WebView2 (Edge/Chromium) | |
| | - macOS: WKWebView (Safari/WebKit) | |
| | - Linux: WebKitGTK | |
| +------------------------------------------------------------+ |
| |
+------------------------------------------------------------------+
|
v
+------------------------------------------------------------------+
| 操作系统 |
| - Windows, macOS, Linux, iOS, Android |
+------------------------------------------------------------------+
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
Tauri 遵循 核心-外壳架构,应用程序被分为两个不同的层:
核心是基于 Rust 的后端,处理所有系统级操作:
核心绝不将直接的系统访问暴露给前端。所有交互都通过经过验证的 IPC 通道进行。
外壳是在 WebView 中渲染的用户界面层:
@tauri-apps/api 调用后端中央协调器,负责:
tauri.conf.jsonTauri 与底层 WebView 库之间的粘合层。抽象了特定平台的 WebView 交互,使 Tauri 的其余部分可以保持平台无关性。
生成编译时代码,用于:
#[tauri::command])跨平台窗口创建库(从 Winit 分支而来):
跨平台 WebView 渲染库:
Tauri 使用 操作系统的原生 WebView,而不是捆绑浏览器引擎:
+-------------------+---------------------------+
| 平台 | WebView 引擎 |
+-------------------+---------------------------+
| Windows | WebView2 (Edge/Chromium) |
| macOS | WKWebView (Safari/WebKit) |
| Linux | WebKitGTK |
| iOS | WKWebView |
| Android | Android WebView |
+-------------------+---------------------------+
Tauri 实现了 异步消息传递 用于前端和后端之间的通信。这比共享内存更安全,因为核心可以拒绝恶意请求。
+------------------+ +------------------+
| 前端 | | Rust 后端 |
| (JavaScript) | | (Core) |
+--------+---------+ +--------+---------+
| |
| 1. invoke('command', {args}) |
+---------------------------------------->|
| |
| [请求序列化为 JSON-RPC] |
| |
| 2. 验证请求 |
| 3. 检查权限 |
| 4. 执行命令 |
| |
| 5. 返回 Result<T, E> |
|<----------------------------------------+
| |
| [响应序列化为 JSON] |
| |
类型安全的前端到后端函数调用:
// Rust 后端
#[tauri::command]
fn greet(name: String) -> String {
format!("Hello, {}!", name)
}
// 在构建器中注册
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![greet])
// JavaScript 前端
import { invoke } from '@tauri-apps/api/core';
const greeting = await invoke('greet', { name: 'World' });
console.log(greeting); // "Hello, World!"
关键特性:
双向、异步通知:
// 前端:发射事件
import { emit } from '@tauri-apps/api/event';
emit('user-action', { action: 'clicked' });
// 前端:监听事件
import { listen } from '@tauri-apps/api/event';
const unlisten = await listen('download-progress', (event) => {
console.log(event.payload);
});
// 后端:监听事件
use tauri::Listener;
app.listen("user-action", |event| {
println!("User action: {}", event.payload());
});
// 后端:发射事件
app.emit("download-progress", 50)?;
关键特性:
Tauri 实现了多层安全措施,以保护应用程序和用户的系统。
+------------------------------------------------------------------+
| 非受信区 |
| +------------------------------------------------------------+ |
| | WebView 前端 | |
| | - JavaScript 代码 (可能来自远程源) | |
| | - 用户输入 | |
| | - 第三方库 | |
| +------------------------------------------------------------+ |
+------------------------------------------------------------------+
|
[信任边界]
[IPC 层验证所有请求]
|
+------------------------------------------------------------------+
| 受信区 |
| +------------------------------------------------------------+ |
| | Rust 后端 | |
| | - 你的 Rust 代码 | |
| | - Tauri 核心 | |
| | - 系统访问 (受权限控制) | |
| +------------------------------------------------------------+ |
+------------------------------------------------------------------+
能力控制授予特定窗口的权限:
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "main-window-capability",
"description": "主应用程序窗口的权限",
"windows": ["main"],
"permissions": [
"core:path:default",
"core:window:allow-set-title",
"fs:read-files",
"fs:scope-app-data"
]
}
能力在 src-tauri/capabilities/ 中定义为 JSON 或 TOML 文件。
Capability
|
+-- windows: ["main", "settings"] // 哪些窗口
|
+-- permissions: // 允许的内容
|
+-- "plugin:action" // 允许特定操作
+-- "plugin:scope-xxx" // 作用域限制
典型的 Tauri 后端遵循以下结构:
src-tauri/
+-- Cargo.toml # Rust 依赖项
+-- tauri.conf.json # Tauri 配置
+-- capabilities/ # 权限定义
| +-- main.json
+-- src/
+-- main.rs # 入口点 (桌面端)
+-- lib.rs # 核心应用逻辑
+-- commands/ # 命令模块
| +-- mod.rs
| +-- file_ops.rs
+-- state.rs # 应用状态管理
// src-tauri/src/lib.rs
mod commands;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.invoke_handler(tauri::generate_handler![
commands::greet,
commands::read_file,
])
.manage(AppState::default())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
// 基本命令
#[tauri::command]
fn simple_command() -> String {
"Hello".into()
}
// 带参数 (JS 使用 camelCase,Rust 使用 snake_case)
#[tauri::command]
fn with_args(user_name: String, age: u32) -> String {
format!("{} is {} years old", user_name, age)
}
// 带错误处理
#[tauri::command]
fn fallible() -> Result<String, String> {
Ok("Success".into())
}
// 异步命令
#[tauri::command]
async fn async_command() -> Result<String, String> {
tokio::time::sleep(Duration::from_secs(1)).await;
Ok("Done".into())
}
// 访问应用状态
#[tauri::command]
fn with_state(state: tauri::State<'_, AppState>) -> String {
state.get_value()
}
// 访问窗口
#[tauri::command]
fn with_window(window: tauri::WebviewWindow) -> String {
window.label().to_string()
}
Tauri 不附带运行时。最终的二进制文件:
这使得逆向工程 Tauri 应用程序比逆向工程捆绑了 JavaScript 的 Electron 应用程序要困难得多。
| 组件 | 角色 |
|---|---|
| 核心 (Rust) | 系统访问、安全性、业务逻辑 |
| 外壳 (前端) | UI 渲染、用户交互 |
| WebView (TAO+WRY) | 平台原生渲染桥接 |
| IPC (命令/事件) | 层间安全的消息传递 |
| 能力 | 每个窗口的权限控制 |
该架构优先考虑:
每周安装量
85
代码仓库
GitHub 星标数
10
首次出现
2026年1月24日
安全审计
安装于
opencode77
gemini-cli76
codex73
github-copilot65
cursor62
claude-code61
Tauri is a polyglot toolkit for building desktop applications that combines a Rust backend with HTML/CSS/JavaScript rendered in a native webview. This document covers the fundamental architecture concepts.
+------------------------------------------------------------------+
| TAURI APPLICATION |
+------------------------------------------------------------------+
| |
| +---------------------------+ +---------------------------+ |
| | FRONTEND (Shell) | | BACKEND (Core) | |
| |---------------------------| |---------------------------| |
| | | | | |
| | HTML / CSS / JavaScript | | Rust Code | |
| | (or any web framework) | | (tauri crate + app) | |
| | | | | |
| | - React, Vue, Svelte, | | - System access | |
| | Solid, etc. | | - File operations | |
| | - Standard web APIs | | - Native features | |
| | - Tauri JS API | | - Plugin system | |
| | | | | |
| +-------------+-------------+ +-------------+-------------+ |
| | | |
| | IPC (Message Passing) | |
| +<------------------------------->+ |
| | Commands & Events | |
| |
| +------------------------------------------------------------+ |
| | WEBVIEW (TAO + WRY) | |
| |------------------------------------------------------------| |
| | - Platform-native webview (not bundled) | |
| | - Windows: WebView2 (Edge/Chromium) | |
| | - macOS: WKWebView (Safari/WebKit) | |
| | - Linux: WebKitGTK | |
| +------------------------------------------------------------+ |
| |
+------------------------------------------------------------------+
|
v
+------------------------------------------------------------------+
| OPERATING SYSTEM |
| - Windows, macOS, Linux, iOS, Android |
+------------------------------------------------------------------+
Tauri follows a Core-Shell architecture where the application is split into two distinct layers:
The Core is the Rust-based backend that handles all system-level operations:
The Core NEVER exposes direct system access to the frontend. All interactions go through validated IPC channels.
The Shell is the user interface layer rendered in a webview:
@tauri-apps/apiThe central orchestrator that:
tauri.conf.json at compile timeThe glue layer between Tauri and lower-level webview libraries. Abstracts platform-specific webview interactions so the rest of Tauri can remain platform-agnostic.
Generate compile-time code for:
#[tauri::command])Cross-platform window creation library (forked from Winit):
Cross-platform WebView rendering library:
Tauri uses the operating system's native webview rather than bundling a browser engine:
+-------------------+---------------------------+
| Platform | WebView Engine |
+-------------------+---------------------------+
| Windows | WebView2 (Edge/Chromium) |
| macOS | WKWebView (Safari/WebKit) |
| Linux | WebKitGTK |
| iOS | WKWebView |
| Android | Android WebView |
+-------------------+---------------------------+
Tauri implements Asynchronous Message Passing for communication between frontend and backend. This is safer than shared memory because the Core can reject malicious requests.
+------------------+ +------------------+
| Frontend | | Rust Backend |
| (JavaScript) | | (Core) |
+--------+---------+ +--------+---------+
| |
| 1. invoke('command', {args}) |
+---------------------------------------->|
| |
| [Request serialized as JSON-RPC] |
| |
| 2. Validate request |
| 3. Check permissions |
| 4. Execute command |
| |
| 5. Return Result<T, E> |
|<----------------------------------------+
| |
| [Response serialized as JSON] |
| |
Type-safe, frontend-to-backend function calls:
// Rust backend
#[tauri::command]
fn greet(name: String) -> String {
format!("Hello, {}!", name)
}
// Register in builder
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![greet])
// JavaScript frontend
import { invoke } from '@tauri-apps/api/core';
const greeting = await invoke('greet', { name: 'World' });
console.log(greeting); // "Hello, World!"
Key characteristics:
Bidirectional, asynchronous notifications:
// Frontend: emit event
import { emit } from '@tauri-apps/api/event';
emit('user-action', { action: 'clicked' });
// Frontend: listen for events
import { listen } from '@tauri-apps/api/event';
const unlisten = await listen('download-progress', (event) => {
console.log(event.payload);
});
// Backend: listen for events
use tauri::Listener;
app.listen("user-action", |event| {
println!("User action: {}", event.payload());
});
// Backend: emit events
app.emit("download-progress", 50)?;
Key characteristics:
Tauri implements multiple layers of security to protect both the application and the user's system.
+------------------------------------------------------------------+
| UNTRUSTED ZONE |
| +------------------------------------------------------------+ |
| | WebView Frontend | |
| | - JavaScript code (potentially from remote sources) | |
| | - User input | |
| | - Third-party libraries | |
| +------------------------------------------------------------+ |
+------------------------------------------------------------------+
|
[TRUST BOUNDARY]
[IPC Layer validates all requests]
|
+------------------------------------------------------------------+
| TRUSTED ZONE |
| +------------------------------------------------------------+ |
| | Rust Backend | |
| | - Your Rust code | |
| | - Tauri core | |
| | - System access (gated by permissions) | |
| +------------------------------------------------------------+ |
+------------------------------------------------------------------+
Capabilities control which permissions are granted to specific windows:
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "main-window-capability",
"description": "Permissions for the main application window",
"windows": ["main"],
"permissions": [
"core:path:default",
"core:window:allow-set-title",
"fs:read-files",
"fs:scope-app-data"
]
}
Capabilities are defined in src-tauri/capabilities/ as JSON or TOML files.
Capability
|
+-- windows: ["main", "settings"] // Which windows
|
+-- permissions: // What's allowed
|
+-- "plugin:action" // Allow specific action
+-- "plugin:scope-xxx" // Scope restrictions
A typical Tauri backend follows this structure:
src-tauri/
+-- Cargo.toml # Rust dependencies
+-- tauri.conf.json # Tauri configuration
+-- capabilities/ # Permission definitions
| +-- main.json
+-- src/
+-- main.rs # Entry point (desktop)
+-- lib.rs # Core app logic
+-- commands/ # Command modules
| +-- mod.rs
| +-- file_ops.rs
+-- state.rs # App state management
// src-tauri/src/lib.rs
mod commands;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.invoke_handler(tauri::generate_handler![
commands::greet,
commands::read_file,
])
.manage(AppState::default())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
// Basic command
#[tauri::command]
fn simple_command() -> String {
"Hello".into()
}
// With arguments (camelCase from JS, snake_case in Rust)
#[tauri::command]
fn with_args(user_name: String, age: u32) -> String {
format!("{} is {} years old", user_name, age)
}
// With error handling
#[tauri::command]
fn fallible() -> Result<String, String> {
Ok("Success".into())
}
// Async command
#[tauri::command]
async fn async_command() -> Result<String, String> {
tokio::time::sleep(Duration::from_secs(1)).await;
Ok("Done".into())
}
// Accessing app state
#[tauri::command]
fn with_state(state: tauri::State<'_, AppState>) -> String {
state.get_value()
}
// Accessing window
#[tauri::command]
fn with_window(window: tauri::WebviewWindow) -> String {
window.label().to_string()
}
Tauri does NOT ship a runtime. The final binary:
This makes reverse engineering Tauri apps non-trivial compared to Electron apps with bundled JavaScript.
| Component | Role |
|---|---|
| Core (Rust) | System access, security, business logic |
| Shell (Frontend) | UI rendering, user interaction |
| WebView (TAO+WRY) | Platform-native rendering bridge |
| IPC (Commands/Events) | Safe message passing between layers |
| Capabilities | Permission control per window |
The architecture prioritizes:
Weekly Installs
85
Repository
GitHub Stars
10
First Seen
Jan 24, 2026
Security Audits
Gen Agent Trust HubFailSocketPassSnykPass
Installed on
opencode77
gemini-cli76
codex73
github-copilot65
cursor62
claude-code61
Kotlin Ktor 服务器模式指南:构建健壮 HTTP API 的架构与最佳实践
1,000 周安装