起動時のコマンドライン引数を取得する

Recipe ID: sys-013

アプリ起動時に渡されたコマンドライン引数を取得する方法を解説します。
Tauri v2 では @tauri-apps/plugin-cli を使用します。

前提条件

プラグインのインストールが必要です。

npm run tauri add cli

Permissions (権限) の設定

src-tauri/capabilities/default.json に以下の権限を追加します。

{
    "permissions": [
        "cli:default",
        ...
    ]
}

tauri.conf.json の設定

プラグイン設定として、受け入れる引数を定義する必要があります。

{
  "plugins": {
    "cli": {
      "description": "My App CLI",
      "args": [
        {
          "name": "verbose",
          "short": "v",
          "description": "Enable verbose logging"
        },
        {
          "name": "input",
          "short": "i",
          "takesValue": true,
          "description": "Input file path"
        }
      ]
    }
  }
}

解説

getMatches() 関数でパース済みの引数を受け取ります。

サンプルコード

import { getMatches } from '@tauri-apps/plugin-cli';

async function checkCliArgs() {
  try {
    const matches = await getMatches();
    
    // フラグ (boolean) の確認
    if (matches.args.verbose?.value) {
      console.log('Verbose mode enabled');
    }

    // 値付き引数の取得
    const inputPath = matches.args.input?.value;
    if (typeof inputPath === 'string') {
      console.log(`Input file: ${inputPath}`);
    }
    
    // 引数全体の内容
    console.log('All args:', matches.args);

  } catch (error) {
    console.error('CLI引数の解析に失敗:', error);
  }
}

checkCliArgs();

実行例

# 開発モードでの実行例
npm run tauri -- dev -- -- -v -i ./data.txt