Skip to content
Tauri 中文网

嵌入附加文件

你可能需要在你的应用包中包含其他文件,这些文件不是你前端(你的 frontendDist)的直接组成部分,或者太大而无法内联到二进制文件中。我们将这些文件称为 resources

¥You may need to include additional files in your application bundle that aren’t part of your frontend (your frontendDist) directly or which are too big to be inlined into the binary. We call these files resources.

要打包你选择的文件,你可以将 resources 属性添加到 tauri.conf.json 文件中的 bundle 对象。

¥To bundle the files of your choice, you can add the resources property to the bundle object in your tauri.conf.json file.

查看 tauri.conf.json此处 参考中的所有可用函数。

¥See more about tauri.conf.json configuration here.

resources 需要一系列字符串,这些字符串以绝对路径或相对路径为目标文件或目录。它支持 glob 模式,以防你需要从目录中包含多个文件。

¥resources expects a list of strings targeting files or directories either with absolute or relative paths. It supports glob patterns in case you need to include multiple files from a directory.

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

¥Here is a sample to illustrate the configuration. This is not a complete tauri.conf.json file:

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

或者,如果你想更改文件将被复制到的位置,resources 配置也接受映射对象。以下是一个示例,展示了如何将来自不同来源的文件包含到同一个 resources 文件夹中:

¥Alternatively the resources config also accepts a map object if you want to change where the files will be copied to. Here is a sample that shows how to include files from different sources into the same resources folder:

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

:::note 注意

在 Tauri 的 权限系统 中,绝对路径和包含父组件 (../) 的路径只能通过 "$RESOURCE/**" 允许。可以通过 "$RESOURCE/path/to/file.txt" 明确允许相对路径(如 "path/to/file.txt")。

¥In Tauri’s permission system, absolute paths and paths containing parent components (../) can only be allowed via "$RESOURCE/**". Relative paths like "path/to/file.txt" can be allowed explicitly via "$RESOURCE/path/to/file.txt".

:::

源路径语法

¥Source path syntax

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

¥In the following explanations “target resource directory” is either the value after the colon in the object notation, or a reconstruction of the original file paths in the array notation.

  • "dir/file.txt":将 file.txt 文件复制到目标资源目录中。

    ¥"dir/file.txt": copies the file.txt file into the target resource directory.

  • "dir/":将所有文件和目录递归复制到目标资源目录中。如果你还想保留文件和目录的文件系统结构,请使用此选项。

    ¥"dir/": copies all files and directories recursively into the target resource directory. Use this if you also want to preserve the file system structure of your files and directories.

  • "dir/*":将 dir 目录中的所有文件非递归地(子目录将被忽略)复制到目标资源目录中。

    ¥"dir/*": copies all files in the dir directory non-recursively (sub-directories will be ignored) into the target resource directory.

  • "dir/**:抛出错误,因为 ** 仅匹配目录,因此找不到文件。

    ¥"dir/**: throws an error because ** only matches directories and therefore no files can be found.

  • "dir/**/*":将 dir 目录中的所有文件递归地(dir/ 中的所有文件和所有子目录中的所有文件)复制到目标资源目录中。

    ¥"dir/**/*": copies all files in the dir directory recursively (all files in dir/ and all files in all sub-directories) into the target resource directory.

  • "dir/**/**:抛出错误,因为 ** 仅匹配目录,因此找不到文件。

    ¥"dir/**/**: throws an error because ** only matches directories and therefore no files can be found.

在 Rust 中访问文件

¥Accessing files in Rust

在此示例中,我们想要打包其他 i18n json 文件,如下所示:

¥In this example we want to bundle additional i18n json files that look like this:

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

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

¥In this case, we store these files in a lang directory next to the tauri.conf.json. For this we add "lang/*" to resources as shown above.

在 Rust 方面,你需要一个 PathResolver 实例,你可以从 AppAppHandle 中获取该实例:

¥On the Rust side, you need an instance of the PathResolver which you can get from App and AppHandle:

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 中访问文件

¥Accessing files in JavaScript

这是基于上述示例。

¥This is based on the example above.

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

¥Note that you must configure the access control list to enable any plugin-fs APIs you will need as well as permissions to access the $RESOURCE folder:

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"
]
}

:::note 注意

以下我们使用 fs:allow-resource-read-recursive 来允许对完整的 $RESOURCE 文件夹、文件和子目录进行完全递归读取访问。有关更多信息,请阅读 范围权限 以了解其他选项,或阅读 范围 以了解更细粒度的控制。

¥Here we use fs:allow-resource-read-recursive to allow for full recursive read access to the complete $RESOURCE folder, files, and subdirectories. For more information, read Scope Permissions for other options, or Scopes for more fine-grained control.

:::

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

Tauri 中文网 - 粤ICP备13048890号