跳转到内容
Tauri

嵌入额外文件

您可能需要在您的应用程序包中包含一些额外的文件,这些文件不属于您的前端(您的 frontendDist),或者文件太大不能内联到二进制文件中。我们称这些文件为 resources

要捆绑您选择的文件,您可以在 tauri.conf.json 文件中添加 resources 属性。

更多关于 tauri.conf.json 配置信息,请参阅 此处

resources 预期一个字符串列表,该列表指定文件或目录,路径可以是绝对路径或相对路径。如果需要从目录中包含多个文件,则支持glob模式。

以下是一个示例,用于说明配置。这不是一个完整的 tauri.conf.json 文件:

tauri.conf.json
{
"bundle": {
"resources": [
"/absolute/path/to/textfile.txt",
"relative/path/to/jsonfile.json",
"resources/**/*"
]
}
}

此外,resources 配置还接受一个映射对象,如果您想更改文件将复制到的位置。以下是一个示例,说明如何将来自不同来源的文件包含到同一个 resources 文件夹中:

tauri.conf.json
{
"bundle": {
"resources": {
"/absolute/path/to/textfile.txt": "resources/textfile.txt",
"relative/path/to/jsonfile.json": "resources/jsonfile.json",
"resources/**/*": "resources/"
}
}
}

源路径语法

在下述解释中,“目标资源目录”是对象表示法中的冒号后面的值,或者是在数组表示法中重建原始文件路径。

  • "dir/file.txt":将 file.txt 文件复制到目标资源目录。
  • "dir/":将所有文件和目录 递归地 复制到目标资源目录。如果您也想保留文件和目录的文件系统结构,请使用此方法。
  • "dir/*":将 dir 目录中的所有文件 非递归地(子目录将被忽略)复制到目标资源目录。
  • "dir/**":引发错误,因为 ** 只匹配目录,因此找不到文件。
  • "dir/**/*":将 dir 目录中的所有文件 递归地(包括 dir/ 中的所有文件以及所有子目录中的所有文件)复制到目标资源目录。
  • "dir/**/**":引发错误,因为 ** 只匹配目录,因此找不到文件。

在 Rust 中访问文件

在此示例中,我们希望捆绑看起来如下所示的附加 i18n json 文件:

de.json
{
"hello": "Guten Tag!",
"bye": "Auf Wiedersehen!"
}

在这种情况下,我们将这些文件存储在 lang 目录中,该目录与 tauri.conf.json 文件相邻。为此,我们将 "lang/*" 添加到上图所示的 resources 中。

在 Rust 端,你需要一个 PathResolver 实例,你可以从 AppAppHandle 获取。

tauri::Builder::default()
.setup(|app| {
// The path specified must follow the same syntax as defined in
// `tauri.conf.json > bundle > resources`
let resource_path = app.path().resolve("lang/de.json", BaseDirectory::Resource)?;
let file = std::fs::File::open(&resource_path).unwrap();
let lang_de: serde_json::Value = serde_json::from_reader(file).unwrap();
// This will print 'Guten Tag!' to the terminal
println!("{}", lang_de.get("hello").unwrap());
Ok(())
})
#[tauri::command]
fn hello(handle: tauri::AppHandle) -> String {
let resource_path = handle.path().resolve("lang/de.json", BaseDirectory::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()
}

在 JavaScript 中访问文件

这基于上面的示例。

请注意,你必须配置访问控制列表,以启用所需的任何 plugin-fs API,以及访问 $RESOURCE 文件夹的权限。

src-tauri/capabilities/default.json
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "main-capability",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"path:default",
"event:default",
"window:default",
"app:default",
"resources:default",
"menu:default",
"tray:default",
"fs:allow-read-text-file",
"fs:allow-resource-read-recursive"
]
}
import { resolveResource } from '@tauri-apps/api/path';
import { readTextFile } from '@tauri-apps/plugin-fs';
const resourcePath = await resolveResource('lang/de.json');
const langDe = JSON.parse(await readTextFile(resourcePath));
console.log(langDe.hello); // This will print 'Guten Tag!' to the devtools console

© 2025 Tauri 贡献者。CC-BY / MIT