跳转到内容
Tauri

命令行界面 (CLI)

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

支持的平台

本插件需要至少 1.77.2 版本的 Rust

平台 级别 备注
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,arg 匹配映射将定义 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 定义为 true,且 occurrences = 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:allow-cli-matches

启用 cli_matches 命令,无需预先配置的作用域。

cli:deny-cli-matches

拒绝 cli_matches 命令,无需预先配置的作用域。


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