跳到内容
Tauri

命令行界面 (CLI)

Tauri 通过强大的命令行参数解析器 clap 使您的应用程序能够拥有 CLI。您只需在 tauri.conf.json 文件中定义一个简单的 CLI 结构,即可定义您的接口,并在 JavaScript 和/或 Rust 中读取其参数匹配映射。

此插件需要 Rust 版本至少为 **1.77.2**

平台 级别 备注
Windows
Linux
macOS
Android
iOS
  • Windows
    • 由于操作系统限制,生产应用默认无法将文本写回调用控制台。请查看 tauri#8305 以获取解决方法。

安装 CLI 插件以开始使用。

使用你的项目包管理器添加依赖项

npm run tauri add cli

tauri.conf.json 中,您可以使用以下结构来配置接口:

src-tauri/tauri.conf.json
{
"plugins": {
"cli": {
"description": "Tauri CLI Plugin Example",
"args": [
{
"short": "v",
"name": "verbose",
"description": "Verbosity level"
}
],
"subcommands": {
"run": {
"description": "Run the application",
"args": [
{
"name": "debug",
"description": "Run application in debug mode"
},
{
"name": "release",
"description": "Run application in release mode"
}
]
}
}
}
}
}

args 数组表示其命令或子命令接受的参数列表。

位置参数通过其在参数列表中的位置来标识。使用以下配置:

src-tauri/tauri.conf.json
{
"args": [
{
"name": "source",
"index": 1,
"takesValue": true
},
{
"name": "destination",
"index": 2,
"takesValue": true
}
]
}

用户可以运行您的应用程序,例如 ./app tauri.txt dest.txt,参数匹配映射将把 source 定义为 "tauri.txt",把 destination 定义为 "dest.txt"

命名参数是 (键, 值) 对,其中键标识值。使用以下配置:

tauri-src/tauri.conf.json
{
"args": [
{
"name": "type",
"short": "t",
"takesValue": true,
"multiple": true,
"possibleValues": ["foo", "bar"]
}
]
}

用户可以运行您的应用程序,例如 ./app --type foo bar./app -t foo -t bar./app --type=foo,bar,参数匹配映射将把 type 定义为 ["foo", "bar"]

标志参数是一个独立的键,其存在或缺失向应用程序提供信息。使用以下配置:

tauri-src/tauri.conf.json
{
"args": [
{
"name": "verbose",
"short": "v"
}
]
}

用户可以运行您的应用程序,例如 ./app -v -v -v./app --verbose --verbose --verbose./app -vvv,参数匹配映射将把 verbose 定义为 trueoccurrences = 3

某些 CLI 应用程序具有作为子命令的附加接口。例如,git CLI 具有 git branchgit commitgit push。您可以使用 subcommands 数组定义额外的嵌套接口:

tauri-src/tauri.conf.json
{
"cli": {
...
"subcommands": {
"branch": {
"args": []
},
"push": {
"args": []
}
}
}
}

其配置与根应用程序配置相同,包括 descriptionlongDescriptionargs 等。

CLI 插件在 JavaScript 和 Rust 中均可用。

import { getMatches } from '@tauri-apps/plugin-cli';
// when using `"withGlobalTauri": true`, you may use
// const { getMatches } = window.__TAURI__.cli;
const matches = await getMatches();
if (matches.subcommand?.name === 'run') {
// `./your-app run $ARGS` was executed
const args = matches.subcommand.matches.args;
if (args.debug?.value === true) {
// `./your-app run --debug` was executed
}
if (args.release?.value === true) {
// `./your-app run --release` was executed
}
}

默认情况下,所有潜在危险的插件命令和范围都被阻止,无法访问。您必须修改 capabilities 配置中的权限才能启用这些功能。

有关更多信息,请参阅功能概述,并参阅分步指南以使用插件权限。

src-tauri/capabilities/default.json
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "main-capability",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": ["cli:default"]
}

默认权限

允许读取 CLI 匹配项

此默认权限集包括以下内容

  • allow-cli-matches

权限表

标识符 描述

启用 cli_matches 命令,不带任何预配置范围。

cli:allow-cli-matches

禁用 cli_matches 命令,不带任何预配置范围。

cli:deny-cli-matches


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