BST Tauri 开发笔记(3)- 打包资源文件

参考:https://tauri.app/v1/guides/building/resources/

编辑 tauri.conf.jsonbundle 下面添加 resources,allowlist里也要添加这一行(如果无需用js访问该文件则不用):

    "bundle": {
      "active": true,
      "icon": [
        "icons/32x32.png",
        "icons/128x128.png",
        "icons/128x128@2x.png",
        "icons/icon.icns",
        "icons/icon.ico"
      ],
      "identifier": "com.cruelyouth.bst-app",
      "targets": "all",
      "resources": [
        "resources/*"
      ]
    },
    "allowlist": {
      "fs": {
        "scope": ["$RESOURCE/*"]
      }
    }

在rust中访问文件

tauri::Builder::default()
  .setup(|app| {
    let resource_path = app.path_resolver()
      .resolve_resource("lang/de.json")
      .expect("failed to resolve resource");

    let file = std::fs::File::open(&resource_path).unwrap();
    let lang_de: serde_json::Value = serde_json::from_reader(file).unwrap();

    println!("{}", lang_de.get("hello").unwrap()); // This will print 'Guten Tag!' to the terminal

    Ok(())
  })

#[tauri::command]
fn hello(handle: tauri::AppHandle) -> String {
   let resource_path = handle.path_resolver()
      .resolve_resource("lang/de.json")
      .expect("failed to resolve resource");

    let file = std::fs::File::open(&resource_path).unwrap();
    let lang_de: serde_json::Value = serde_json::from_reader(file).unwrap();

    lang_de.get("hello").unwrap().to_string()
}

该文件夹下放入一个文件,打包试试 npm run tauri build 打包后的可执行文件中嵌入了该资源文件。

发表回复