跳到主要內容

嵌入其他檔案

您可能需要在應用程式套件中包含其他檔案,這些檔案並非直接屬於您的前端(您的 distDir),或檔案太大而無法內嵌到二進位檔中。我們稱這些檔案為「資源」。

若要將您選擇的檔案打包,您可以在 tauri.conf.json 檔案中的 tauri > bundle 物件中新增 resources 屬性。

在此處查看有關 tauri.conf.json 組態的更多資訊 here

resources 預期會有一個字串清單,目標檔案具有絕對或相對路徑。它支援 glob 模式,以防您需要包含目錄中的多個檔案。

以下是一個說明組態的範例。這不是完整的 tauri.conf.json 檔案

tauri.conf.json
{
"tauri": {
"bundle": {
"resources": [
"/absolute/path/to/textfile.txt",
"relative/path/to/jsonfile.json",
"resources/*"
]
},
"allowlist": {
"fs": {
"scope": ["$RESOURCE/*"]
}
}
}
}
注意

絕對路徑和包含父元件 (../) 的路徑只能透過 "$RESOURCE/*" 允許。相對路徑 (例如 "path/to/file.txt") 可以透過 "$RESOURCE/path/to/file.txt" 明確允許。

在 JavaScript 中存取檔案

在此範例中,我們要將看起來像這樣的其他 i18n json 檔案打包

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

在這種情況下,我們將這些檔案儲存在 tauri.conf.json 旁邊的 lang 目錄中。為此,我們將 "lang/*" 新增至 resources,並將 $RESOURCE/lang/* 新增至 fs 範圍,如上所示。

請注意,您必須設定允許清單,才能啟用 path > all 和您需要的 fs API,在此範例中為 fs > readTextFile

import { resolveResource } from '@tauri-apps/api/path'
// alternatively, use `window.__TAURI__.path.resolveResource`
import { readTextFile } from '@tauri-apps/api/fs'
// alternatively, use `window.__TAURI__.fs.readTextFile`

// `lang/de.json` is the value specified on `tauri.conf.json > tauri > bundle > resources`
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

在 Rust 中存取檔案

這基於上述範例。在 Rust 端,您需要 PathResolver 的執行個體,您可以從 AppAppHandle 取得。

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()
}