嵌入附加文件
您可能需要在应用程序包中包含附加文件,这些文件不直接属于您的前端(您的 frontendDist
),或者太大而无法内联到二进制文件中。我们将这些文件称为 resources
。
要打包您选择的文件,您可以将 resources
属性添加到您的 tauri.conf.json
文件中的 bundle
对象。
在此处查看更多关于 tauri.conf.json
配置的信息:此处。
resources
期望一个字符串列表,这些字符串使用绝对路径或相对路径指向文件或目录。它支持 glob 模式,以防您需要包含来自目录的多个文件。
这是一个示例,用于说明配置。这并不是一个完整的 tauri.conf.json
文件
{ "bundle": { "resources": [ "/absolute/path/to/textfile.txt", "relative/path/to/jsonfile.json", "resources/**/*" ] }}
或者,如果您想更改文件将被复制到的位置,resources
配置也接受一个映射对象。这是一个示例,展示了如何将来自不同源的文件包含到同一个 resources
文件夹中
{ "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/**/**
:会抛出错误,因为**
只匹配目录,因此找不到文件。
在这个例子中,我们想要打包额外的 i18n json 文件,它们看起来像这样:
{ "hello": "Guten Tag!", "bye": "Auf Wiedersehen!"}
在这种情况下,我们将这些文件存储在 tauri.conf.json
旁边的 lang
目录中。为此,我们将 "lang/*"
添加到 resources
中,如上所示。
在 Rust 侧,您需要一个 PathResolver
实例,您可以从 App
和 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 方面,您可以使用如上所示的命令并通过 await invoke('hello')
调用它,或者使用 plugin-fs
访问文件
在使用 plugin-fs
时,除了基本设置之外,您还需要配置访问控制列表以启用您需要的任何 plugin-fs
API 以及访问 $RESOURCE
文件夹的权限
{ "$schema": "../gen/schemas/desktop-schema.json", "identifier": "main-capability", "description": "Capability for the main window", "windows": ["main"], "permissions": [ "core: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