跳到内容
Tauri

嵌入外部二进制文件

您可能需要嵌入外部二进制文件,以向您的应用程序添加额外的功能,或防止用户安装额外的依赖项(例如 Node.js 或 Python)。我们将此二进制文件称为 sidecar

二进制文件是用任何编程语言编写的可执行文件。常见的用例是使用 pyinstaller 打包的 Python CLI 应用程序或 API 服务器。

要捆绑您选择的二进制文件,您可以将 externalBin 属性添加到 tauri > bundle 对象中的 tauri.conf.jsonexternalBin 配置需要一个字符串列表,目标二进制文件可以是绝对路径或相对路径。

这是一个 Tauri 配置文件片段,用于说明 sidecar 配置

src-tauri/tauri.conf.json
{
"bundle": {
"externalBin": [
"/absolute/path/to/sidecar",
"../relative/path/to/binary",
"binaries/my-sidecar"
]
}
}

为了使外部二进制文件在每个受支持的架构上都能工作,在指定的路径上必须存在具有相同名称和 -$TARGET_TRIPLE 后缀的二进制文件。例如,"externalBin": ["binaries/my-sidecar"] 需要在 Linux 上有一个 src-tauri/binaries/my-sidecar-x86_64-unknown-linux-gnu 可执行文件,或者在配备 Apple 芯片的 Mac OS 上需要 src-tauri/binaries/my-sidecar-aarch64-apple-darwin 可执行文件。

您可以通过查看以下命令报告的 host: 属性来找到您当前平台的 -$TARGET_TRIPLE 后缀

终端窗口
rustc -Vv

如果 grepcut 命令可用(在大多数 Unix 系统上应该是可用的),您可以使用以下命令直接提取目标三元组

终端窗口
rustc -Vv | grep host | cut -f2 -d' '

在 Windows 上,您可以使用 PowerShell 代替

终端窗口
rustc -Vv | Select-String "host:" | ForEach-Object {$_.Line.split(" ")[1]}

这是一个 Node.js 脚本,用于将目标三元组附加到二进制文件

import { execSync } from 'child_process';
import fs from 'fs';
const extension = process.platform === 'win32' ? '.exe' : '';
const rustInfo = execSync('rustc -vV');
const targetTriple = /host: (\S+)/g.exec(rustInfo)[1];
if (!targetTriple) {
console.error('Failed to determine platform target triple');
}
fs.renameSync(
`src-tauri/binaries/sidecar${extension}`,
`src-tauri/binaries/sidecar-${targetTriple}${extension}`
);

请注意,如果您编译的目标架构与脚本运行的架构不同,则此脚本将无法工作,因此仅将其用作您自己的构建脚本的起点。

从 Rust 运行

在 Rust 端,导入 tauri_plugin_shell::ShellExt trait 并在 AppHandle 上调用 shell().sidecar() 函数

use tauri_plugin_shell::ShellExt;
use tauri_plugin_shell::process::CommandEvent;
let sidecar_command = app.shell().sidecar("my-sidecar").unwrap();
let (mut rx, mut _child) = sidecar_command
.spawn()
.expect("Failed to spawn sidecar");
tauri::async_runtime::spawn(async move {
// read events such as stdout
while let Some(event) = rx.recv().await {
if let CommandEvent::Stdout(line_bytes) = event {
let line = String::from_utf8_lossy(&line_bytes);
window
.emit("message", Some(format!("'{}'", line)))
.expect("failed to emit event");
// write to stdin
child.write("message from Rust\n".as_bytes()).unwrap();
}
}
});

您可以将此代码放在 Tauri 命令中以轻松传递 AppHandle,或者您可以将 AppHandle 的引用存储在构建器脚本中,以便在应用程序的其他位置访问它。

从 JavaScript 运行

运行 sidecar 时,Tauri 要求您授予 sidecar 权限以在子进程上运行 executespawn 方法。要授予此权限,请转到文件 <PROJECT ROOT>/src-tauri/capabilities/default.json,并将以下部分添加到 permissions 数组。不要忘记根据前面提到的相对路径命名您的 sidecar。

src-tauri/capabilities/default.json
{
"permissions": [
"core:default",
{
"identifier": "shell:allow-execute",
"allow": [
{
"name": "binaries/app",
"sidecar": true
}
]
},
"shell:allow-open"
]
}

在 JavaScript 代码中,从 @tauri-apps/plugin-shell 模块导入 Command 类,并使用 sidecar 静态方法。

import { Command } from '@tauri-apps/plugin-shell';
const command = Command.sidecar('binaries/my-sidecar');
const output = await command.execute();

传递参数

您可以像运行正常的 Command 一样,将参数传递给 Sidecar 命令。

参数可以是静态的(例如 -oserve)或动态的(例如 <file_path>localhost:<PORT>)。您按照调用它们的精确顺序定义参数。静态参数按原样定义,而动态参数可以使用正则表达式定义。

首先,在 src-tauri/capabilities/default.json 中定义需要传递给 sidecar 命令的参数

src-tauri/capabilities/default.json
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
{
"identifier": "shell:allow-execute",
"allow": [
{
"args": [
"arg1",
"-a",
"--arg2",
{
"validator": "\\S+"
}
],
"name": "binaries/my-sidecar",
"sidecar": true
}
]
},
"shell:allow-open"
]
}

然后,要调用 sidecar 命令,只需传入所有参数作为数组即可。

在 Rust 中

use tauri_plugin_shell::ShellExt;
#[tauri::command]
async fn call_my_sidecar(app: tauri::AppHandle) {
let sidecar_command = app
.shell()
.sidecar("my-sidecar")
.unwrap()
.args(["arg1", "-a", "--arg2", "any-string-that-matches-the-validator"]);
let (mut _rx, mut _child) = sidecar_command.spawn().unwrap();
}

在 JavaScript 中

import { Command } from '@tauri-apps/plugin-shell';
// notice that the args array matches EXACTLY what is specified in `capabilities/default.json`.
const command = Command.sidecar('binaries/my-sidecar', [
'arg1',
'-a',
'--arg2',
'any-string-that-matches-the-validator',
]);
const output = await command.execute();

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