mcpField
M
managing-tauri-app-resources

managing-tauri-app-resources

github.com/dchuk开发36163 次安装40 周前更新
代码仓库

关于 managing-tauri-app-resources

面向 Tauri 开发者的资源与状态管理参考指南,介绍平台图标生成、静态文件打包与访问,以及在命令和处理器间共享应用状态。

主要功能

  1. 01生成各平台所需图标
  2. 02静态资源打包模式
  3. 03通过 Rust 和 JavaScript 访问资源
  4. 04资源访问权限配置
  5. 05共享及可变状态模式

适用场景

  1. 01生成 Tauri 应用的平台图标
  2. 02将文件打包进 Tauri 应用
  3. 03在 Rust 或 JavaScript 中读取内置资源
  4. 04管理 Tauri 命令间的应用状态

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/dchuk/claude-code-tauri-skills --skill managing-tauri-app-resources

安装后在 Claude Code 中输入/managing-tauri-app-resources确认已加载。

详细介绍

管理 Tauri 应用资源

应用图标

图标生成

从单个源文件生成所有特定于平台的图标:

cargo tauri icon              # Default: ./app-icon.png
cargo tauri icon ./custom.png -o ./icons  # Custom source/output
cargo tauri icon --ios-color "#000000"    # iOS background color

**源文件要求:**带透明背景的正方形 PNG 或 SVG。

生成的格式
格式平台
icon.icnsmacOS
icon.icoWindows
*.pngLinux、Android、iOS
配置
{
  "bundle": {
    "icon": [
      "icons/32x32.png",
      "icons/128x128.png",
      "icons/[email protected]",
      "icons/icon.icns",
      "icons/icon.ico"
    ]
  }
}
平台要求

**Windows (.ico):**包含 16、24、32、48、64、256 像素的图层。

**Android:**不能包含透明背景。放置在 src-tauri/gen/android/app/src/main/res/mipmap-* 文件夹中。每个文件夹都需要 ic_launcher.png、ic_launcher_round.png、ic_launcher_foreground.png。

**iOS:**不能包含透明背景。放置在 src-tauri/gen/apple/Assets.xcassets/AppIcon.appiconset/ 中。所需尺寸:20、29、40、60、76、83.5 像素,支持 1x/2x/3x 比例,另需 512x512@2x。


嵌入静态资源

配置

数组语法(保留目录结构):

{
  "bundle": {
    "resources": ["./file.txt", "folder/", "docs/**/*.md"]
  }
}

映射语法(自定义目标路径):

{
  "bundle": {
    "resources": {
      "path/to/source.json": "resources/dest.json",
      "docs/**/*.md": "website-docs/"
    }
  }
}
路径模式
模式行为
"dir/file.txt"单个文件
"dir/"递归遍历目录
"dir/*"非递归遍历文件
"dir/**/*"递归遍历所有文件
访问资源 - Rust
use tauri::Manager;
use tauri::path::BaseDirectory;

#[tauri::command]
fn load_resource(handle: tauri::AppHandle) -> Result<String, String> {
    let path = handle
        .path()
        .resolve("lang/de.json", BaseDirectory::Resource)
        .map_err(|e| e.to_string())?;
    std::fs::read_to_string(&path).map_err(|e| e.to_string())
}
访问资源 - JavaScript
import { resolveResource } from '@tauri-apps/api/path';
import { readTextFile } from '@tauri-apps/plugin-fs';

const resourcePath = await resolveResource('lang/de.json');
const content = await readTextFile(resourcePath);
const data = JSON.parse(content);
权限
{
  "permissions": [
    "fs:allow-read-text-file",
    "fs:allow-resource-read-recursive"
  ]
}

递归访问时使用 $RESOURCE/**/* 范围。


状态管理

基本设置
use tauri::{Builder, Manager};

struct AppData {
    welcome_message: &'static str,
}

fn main() {
    Builder::default()
        .setup(|app| {
            app.manage(AppData {
                welcome_message: "Welcome!",
            });
            Ok(())
        })
        .run(tauri::generate_context!())
        .unwrap()
}
线程安全的可变状态
use std::sync::Mutex;
use tauri::{Builder, Manager};

#[derive(Default)]
struct AppState {
    counter: u32,
}

fn main() {
    Builder::default()
        .setup(|app| {
            app.manage(Mutex::new(AppState::default()));
            Ok(())
        })
        .run(tauri::generate_context!())
        .unwrap()
}
在命令中访问状态
use std::sync::Mutex;
use tauri::State;

#[tauri::command]
fn increase_counter(state: State<'_, Mutex<AppState>>) -> u32 {
    let mut state = state.lock().unwrap();
    state.counter += 1;
    state.counter
}

#[tauri::command]
fn get_counter(state: State<'_, Mutex<AppState>>) -> u32 {
    state.lock().unwrap().counter
}
使用 Tokio Mutex 的异步命令
use tokio::sync::Mutex;
use tauri::State;

#[tauri::command]
async fn increase_counter_async(
    state: State<'_, Mutex<AppState>>
) -> Result<u32, ()> {
    let mut state = state.lock().await;
    state.counter += 1;
    Ok(state.counter)
}
在命令外访问状态
use std::sync::Mutex;
use tauri::{Manager, Window, WindowEvent};

fn on_window_event(window: &Window, event: &WindowEvent) {
    let app_handle = window.app_handle();
    let state = app_handle.state::<Mutex<AppState>>();
    let mut state = state.lock().unwrap();
    state.counter += 1;
}
类型别名模式

防止因类型不匹配导致的运行时 panic:

use std::sync::Mutex;

struct AppStateInner {
    counter: u32,
}

type AppState = Mutex<AppStateInner>;

#[tauri::command]
fn get_counter(state: State<'_, AppState>) -> u32 {
    state.lock().unwrap().counter
}
多种状态类型
use std::sync::Mutex;
use tauri::{Builder, Manager, State};

struct UserState { username: Option<String> }
struct AppSettings { theme: String }

fn main() {
    Builder::default()
        .setup(|app| {
            app.manage(Mutex::new(UserState { username: None }));
            app.manage(Mutex::new(AppSettings { theme: "dark".into() }));
            Ok(())
        })
        .run(tauri::generate_context!())
        .unwrap()
}

#[tauri::command]
fn login(user_state: State<'_, Mutex<UserState>>, username: String) {
    user_state.lock().unwrap().username = Some(username);
}

#[tauri::command]
fn set_theme(settings: State<'_, Mutex<AppSettings>>, theme: String) {
    settings.lock().unwrap().theme = theme;
}
要点
  • 不需要 Arc——Tauri 会在内部处理引用计数
  • 大多数情况下使用 std::sync::Mutex;只有在 await 点之间持有锁时才使用 Tokio 的互斥锁
  • 类型安全——状态类型错误会导致运行时 panic,而非编译错误;请使用类型别名

完整示例

tauri.conf.json:

{
  "bundle": {
    "icon": [
      "icons/32x32.png",
      "icons/128x128.png",
      "icons/icon.icns",
      "icons/icon.ico"
    ],
    "resources": {
      "assets/config.json": "config.json",
      "assets/translations/": "lang/"
    }
  }
}

src-tauri/src/main.rs:

use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use tauri::{Builder, Manager, State};
use tauri::path::BaseDirectory;

#[derive(Default)]
struct AppState { counter: u32, locale: String }
type ManagedState = Mutex<AppState>;

#[derive(Serialize, Deserialize)]
struct Config { app_name: String, version: String }

#[tauri::command]
fn increment(state: State<'_, ManagedState>) -> u32 {
    let mut s = state.lock().unwrap();
    s.counter += 1;
    s.counter
}

#[tauri::command]
fn load_config(handle: tauri::AppHandle) -> Result<Config, String> {
    let path = handle.path()
        .resolve("config.json", BaseDirectory::Resource)
        .map_err(|e| e.to_string())?;
    let content = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
    serde_json::from_str(&content).map_err(|e| e.to_string())
}

fn main() {
    Builder::default()
        .setup(|app| {
            app.manage(Mutex::new(AppState::default()));
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![increment, load_config])
        .run(tauri::generate_context!())
        .unwrap()
}

前端:

import { invoke } from '@tauri-apps/api/core';
import { resolveResource } from '@tauri-apps/api/path';
import { readTextFile } from '@tauri-apps/plugin-fs';

const newValue = await invoke('increment');
const config = await invoke('load_config');
const langPath = await resolveResource('lang/en.json');
const translations = JSON.parse(await readTextFile(langPath));

快速参考

图标命令
cargo tauri icon                    # Generate from ./app-icon.png
cargo tauri icon ./icon.png -o out  # Custom source/output
资源模式
{ "resources": ["data.json"] }              // Single file
{ "resources": ["assets/"] }                // Directory recursive
{ "resources": { "src/x.json": "x.json" }}  // Custom destination
状态模式
app.manage(Config { ... });              // Immutable
app.manage(Mutex::new(State { ... }));   // Mutable
fn cmd(state: State<'_, Mutex<T>>)       // In command
app_handle.state::<Mutex<T>>()           // Via AppHandle

评论

支持 Markdown