跳到內容
Tauri

嵌入額外檔案

您可能需要在應用程式套件中包含額外檔案,這些檔案並非直接屬於您的前端(您的 frontendDist),或檔案過大而無法內嵌到二進制檔案中。我們將這些檔案稱為 resources(資源)。

若要捆綁您選擇的檔案,您可以將 resources 屬性新增至您的 tauri.conf.json 檔案中的 bundle 物件。

請參閱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 組態也接受 map 物件。以下範例說明如何將來自不同來源的檔案包含到同一個 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!"
}

在此情況下,我們將這些檔案儲存在 tauri.conf.json 旁邊的 lang 目錄中。為此,我們將 "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