debugging-tauri-apps

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Debugging Tauri Applications

调试Tauri应用程序

This skill covers debugging Tauri v2 applications including console debugging, WebView inspection, IDE configurations, and CrabNebula DevTools.
本技能涵盖Tauri v2应用程序的调试方法,包括控制台调试、WebView检查、IDE配置以及CrabNebula DevTools的使用。

Development-Only Code

仅开发环境代码

Use conditional compilation to exclude debug code from production builds:
rust
// Only runs during `tauri dev`
#[cfg(dev)]
{
    // Development-only code
}

// Runtime check
if cfg!(dev) {
    // tauri dev code
} else {
    // tauri build code
}

// Programmatic check
let is_dev: bool = tauri::is_dev();

// Debug builds and `tauri build --debug`
#[cfg(debug_assertions)]
{
    // Debug-only code
}
使用条件编译将调试代码从生产构建中排除:
rust
// Only runs during `tauri dev`
#[cfg(dev)]
{
    // Development-only code
}

// Runtime check
if cfg!(dev) {
    // tauri dev code
} else {
    // tauri build code
}

// Programmatic check
let is_dev: bool = tauri::is_dev();

// Debug builds and `tauri build --debug`
#[cfg(debug_assertions)]
{
    // Debug-only code
}

Console Debugging

控制台调试

Rust Print Macros

Rust打印宏

Print messages to the terminal where
tauri dev
runs:
rust
println!("Message from Rust: {}", msg);
dbg!(&variable);  // Prints variable with file:line info
将消息打印到
tauri dev
运行的终端:
rust
println!("Message from Rust: {}", msg);
dbg!(&variable);  // Prints variable with file:line info

Enable Backtraces

启用回溯功能

For detailed error information:
bash
undefined
获取详细的错误信息:
bash
undefined

Linux/macOS

Linux/macOS

RUST_BACKTRACE=1 tauri dev
RUST_BACKTRACE=1 tauri dev

Windows PowerShell

Windows PowerShell

$env:RUST_BACKTRACE=1 tauri dev
undefined
$env:RUST_BACKTRACE=1 tauri dev
undefined

WebView DevTools

WebView DevTools

Opening DevTools

打开DevTools

  • Right-click and select "Inspect Element"
  • Ctrl + Shift + i
    (Linux/Windows)
  • Cmd + Option + i
    (macOS)
Platform-specific inspectors: WebKit (Linux), Safari (macOS), Edge DevTools (Windows).
  • 右键点击并选择“检查元素”
  • Ctrl + Shift + i
    (Linux/Windows)
  • Cmd + Option + i
    (macOS)
各平台对应的检查器:WebKit(Linux)、Safari(macOS)、Edge DevTools(Windows)。

Programmatic Control

程序化控制

rust
tauri::Builder::default()
    .setup(|app| {
        #[cfg(debug_assertions)]
        {
            let window = app.get_webview_window("main").unwrap();
            window.open_devtools();
            // window.close_devtools();
        }
        Ok(())
    })
rust
tauri::Builder::default()
    .setup(|app| {
        #[cfg(debug_assertions)]
        {
            let window = app.get_webview_window("main").unwrap();
            window.open_devtools();
            // window.close_devtools();
        }
        Ok(())
    })

Production DevTools

生产环境启用DevTools

Create a debug build for testing:
bash
tauri build --debug
To permanently enable devtools in production, add to
src-tauri/Cargo.toml
:
toml
[dependencies]
tauri = { version = "...", features = ["...", "devtools"] }
WARNING: Using the devtools feature enables private macOS APIs that prevent App Store acceptance.

创建调试构建用于测试:
bash
tauri build --debug
要在生产环境中永久启用DevTools,需添加到
src-tauri/Cargo.toml
toml
[dependencies]
tauri = { version = "...", features = ["...", "devtools"] }
警告:使用devtools功能会启用私有macOS API,导致应用无法通过App Store审核。

VS Code Setup

VS Code设置

Required Extensions

所需扩展

ExtensionPlatformPurpose
vscode-lldbAllLLDB debugger
C/C++WindowsVisual Studio debugger
扩展平台用途
vscode-lldb所有平台LLDB调试器
C/C++WindowsVisual Studio调试器

launch.json Configuration

launch.json配置

Create
.vscode/launch.json
:
json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "lldb",
      "request": "launch",
      "name": "Tauri Development Debug",
      "cargo": {
        "args": [
          "build",
          "--manifest-path=./src-tauri/Cargo.toml",
          "--no-default-features"
        ]
      },
      "preLaunchTask": "ui:dev"
    },
    {
      "type": "lldb",
      "request": "launch",
      "name": "Tauri Production Debug",
      "cargo": {
        "args": [
          "build",
          "--release",
          "--manifest-path=./src-tauri/Cargo.toml"
        ]
      },
      "preLaunchTask": "ui:build"
    }
  ]
}
创建
.vscode/launch.json
json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "lldb",
      "request": "launch",
      "name": "Tauri Development Debug",
      "cargo": {
        "args": [
          "build",
          "--manifest-path=./src-tauri/Cargo.toml",
          "--no-default-features"
        ]
      },
      "preLaunchTask": "ui:dev"
    },
    {
      "type": "lldb",
      "request": "launch",
      "name": "Tauri Production Debug",
      "cargo": {
        "args": [
          "build",
          "--release",
          "--manifest-path=./src-tauri/Cargo.toml"
        ]
      },
      "preLaunchTask": "ui:build"
    }
  ]
}

Windows Visual Studio Debugger

Windows Visual Studio调试器

For faster Windows debugging with better enum support:
json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch App Debug",
      "type": "cppvsdbg",
      "request": "launch",
      "program": "${workspaceRoot}/src-tauri/target/debug/your-app-name.exe",
      "cwd": "${workspaceRoot}",
      "preLaunchTask": "dev"
    }
  ]
}
为Windows平台提供更快的调试速度和更好的枚举支持:
json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch App Debug",
      "type": "cppvsdbg",
      "request": "launch",
      "program": "${workspaceRoot}/src-tauri/target/debug/your-app-name.exe",
      "cwd": "${workspaceRoot}",
      "preLaunchTask": "dev"
    }
  ]
}

tasks.json Configuration

tasks.json配置

Create
.vscode/tasks.json
:
json
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "ui:dev",
      "type": "shell",
      "isBackground": true,
      "command": "npm",
      "args": ["run", "dev"]
    },
    {
      "label": "ui:build",
      "type": "shell",
      "command": "npm",
      "args": ["run", "build"]
    },
    {
      "label": "build:debug",
      "type": "cargo",
      "command": "build",
      "options": {
        "cwd": "${workspaceRoot}/src-tauri"
      }
    },
    {
      "label": "dev",
      "dependsOn": ["build:debug", "ui:dev"],
      "group": {
        "kind": "build"
      }
    }
  ]
}
创建
.vscode/tasks.json
json
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "ui:dev",
      "type": "shell",
      "isBackground": true,
      "command": "npm",
      "args": ["run", "dev"]
    },
    {
      "label": "ui:build",
      "type": "shell",
      "command": "npm",
      "args": ["run", "build"]
    },
    {
      "label": "build:debug",
      "type": "cargo",
      "command": "build",
      "options": {
        "cwd": "${workspaceRoot}/src-tauri"
      }
    },
    {
      "label": "dev",
      "dependsOn": ["build:debug", "ui:dev"],
      "group": {
        "kind": "build"
      }
    }
  ]
}

Debugging Workflow

调试工作流

  1. Set breakpoints by clicking the line number margin in Rust files
  2. Press
    F5
    or select debug configuration from Run menu
  3. The
    preLaunchTask
    runs the dev server automatically
  4. Debugger attaches and stops at breakpoints
NOTE: LLDB bypasses the Tauri CLI, so
beforeDevCommand
and
beforeBuildCommand
must be configured as tasks.

  1. 在Rust文件的行号边距点击设置断点
  2. F5
    或从运行菜单中选择调试配置
  3. preLaunchTask
    会自动启动开发服务器
  4. 调试器会附加到进程并在断点处停止
注意:LLDB会绕过Tauri CLI,因此
beforeDevCommand
beforeBuildCommand
必须配置为任务。

RustRover / IntelliJ Setup

RustRover / IntelliJ设置

Project Configuration

项目配置

If your project lacks a top-level
Cargo.toml
, create a workspace file:
toml
[workspace]
members = ["src-tauri"]
Or attach
src-tauri/Cargo.toml
via the Cargo tool window.
如果项目缺少顶级
Cargo.toml
,请创建一个工作区文件:
toml
[workspace]
members = ["src-tauri"]
或者通过Cargo工具窗口附加
src-tauri/Cargo.toml

Run Configurations

运行配置

Create two configurations in Run | Edit Configurations:
运行 | 编辑配置中创建两个配置:

1. Tauri App Configuration (Cargo)

1. Tauri应用配置(Cargo)

  • Command:
    run
  • Additional arguments:
    --no-default-features
The
--no-default-features
flag is critical - it tells Tauri to load assets from the dev server instead of bundling them.
  • 命令
    run
  • 附加参数
    --no-default-features
--no-default-features
标志非常关键——它告诉Tauri从开发服务器加载资源,而不是打包资源。

2. Development Server Configuration

2. 开发服务器配置

For Node-based projects:
  • Create an npm Run Configuration
  • Set package manager (npm/pnpm/yarn)
  • Set script to
    dev
For Rust WASM (Trunk):
  • Create a Shell Script configuration
  • Command:
    trunk serve
对于基于Node的项目:
  • 创建一个npm运行配置
  • 设置包管理器(npm/pnpm/yarn)
  • 设置脚本为
    dev
对于Rust WASM(Trunk):
  • 创建一个Shell脚本配置
  • 命令:
    trunk serve

Debugging Workflow

调试工作流

  1. Start the development server configuration first
  2. Click Debug on the Tauri App configuration
  3. RustRover halts at Rust breakpoints automatically
  4. Inspect variables and step through code

  1. 先启动开发服务器配置
  2. 点击Tauri应用配置的调试按钮
  3. RustRover会自动在Rust断点处暂停
  4. 检查变量并单步执行代码

Neovim Setup

Neovim设置

Required Plugins

所需插件

  • nvim-dap - Debug Adapter Protocol client
  • nvim-dap-ui - Debugger UI
  • nvim-nio - Async dependency for nvim-dap-ui
  • overseer.nvim (recommended) - Task management
  • nvim-dap - Debug Adapter Protocol客户端
  • nvim-dap-ui - 调试器UI
  • nvim-nio - nvim-dap-ui的异步依赖
  • overseer.nvim(推荐)- 任务管理工具

Prerequisites

前置条件

Download
codelldb
from GitHub releases and note the installation path.
GitHub releases下载
codelldb
并记录安装路径。

DAP Configuration

DAP配置

Add to your Neovim config (init.lua or equivalent):
lua
local dap = require("dap")

-- Configure codelldb adapter
dap.adapters.codelldb = {
  type = 'server',
  port = "${port}",
  executable = {
    command = '/path/to/codelldb/adapter/codelldb',
    args = {"--port", "${port}"},
  }
}

-- Launch configuration for Rust/Tauri
dap.configurations.rust = {
  {
    name = "Launch Tauri App",
    type = "codelldb",
    request = "launch",
    program = function()
      return vim.fn.input('Path to executable: ', vim.fn.getcwd() .. '/target/debug/', 'file')
    end,
    cwd = '${workspaceFolder}',
    stopOnEntry = false
  },
}
添加到你的Neovim配置文件(init.lua或等效文件):
lua
local dap = require("dap")

-- Configure codelldb adapter
dap.adapters.codelldb = {
  type = 'server',
  port = "${port}",
  executable = {
    command = '/path/to/codelldb/adapter/codelldb',
    args = {"--port", "${port}"},
  }
}

-- Launch configuration for Rust/Tauri
dap.configurations.rust = {
  {
    name = "Launch Tauri App",
    type = "codelldb",
    request = "launch",
    program = function()
      return vim.fn.input('Path to executable: ', vim.fn.getcwd() .. '/target/debug/', 'file')
    end,
    cwd = '${workspaceFolder}',
    stopOnEntry = false
  },
}

UI Integration

UI集成

lua
local dapui = require("dapui")
dapui.setup()

-- Auto-open/close UI
dap.listeners.before.attach.dapui_config = function()
  dapui.open()
end
dap.listeners.before.launch.dapui_config = function()
  dapui.open()
end
dap.listeners.before.event_terminated.dapui_config = function()
  dapui.close()
end
dap.listeners.before.event_exited.dapui_config = function()
  dapui.close()
end
lua
local dapui = require("dapui")
dapui.setup()

-- Auto-open/close UI
dap.listeners.before.attach.dapui_config = function()
  dapui.open()
end
dap.listeners.before.launch.dapui_config = function()
  dapui.open()
end
dap.listeners.before.event_terminated.dapui_config = function()
  dapui.close()
end
dap.listeners.before.event_exited.dapui_config = function()
  dapui.close()
end

Visual Indicators

视觉指示器

lua
vim.fn.sign_define('DapBreakpoint', {
  text = 'B',
  texthl = 'DapBreakpoint',
  linehl = '',
  numhl = ''
})
vim.fn.sign_define('DapStopped', {
  text = '>',
  texthl = 'DapStopped',
  linehl = 'DapStopped',
  numhl = ''
})
lua
vim.fn.sign_define('DapBreakpoint', {
  text = 'B',
  texthl = 'DapBreakpoint',
  linehl = '',
  numhl = ''
})
vim.fn.sign_define('DapStopped', {
  text = '>',
  texthl = 'DapStopped',
  linehl = 'DapStopped',
  numhl = ''
})

Keybindings

按键绑定

lua
vim.keymap.set('n', '<F5>', function() dap.continue() end)
vim.keymap.set('n', '<F6>', function() dap.disconnect({ terminateDebuggee = true }) end)
vim.keymap.set('n', '<F10>', function() dap.step_over() end)
vim.keymap.set('n', '<F11>', function() dap.step_into() end)
vim.keymap.set('n', '<F12>', function() dap.step_out() end)
vim.keymap.set('n', '<Leader>b', function() dap.toggle_breakpoint() end)
vim.keymap.set('n', '<Leader>o', function() overseer.toggle() end)
vim.keymap.set('n', '<Leader>R', function() overseer.run_template() end)
lua
vim.keymap.set('n', '<F5>', function() dap.continue() end)
vim.keymap.set('n', '<F6>', function() dap.disconnect({ terminateDebuggee = true }) end)
vim.keymap.set('n', '<F10>', function() dap.step_over() end)
vim.keymap.set('n', '<F11>', function() dap.step_into() end)
vim.keymap.set('n', '<F12>', function() dap.step_out() end)
vim.keymap.set('n', '<Leader>b', function() dap.toggle_breakpoint() end)
vim.keymap.set('n', '<Leader>o', function() overseer.toggle() end)
vim.keymap.set('n', '<Leader>R', function() overseer.run_template() end)

Development Server Task

开发服务器任务

Create
.vscode/tasks.json
for overseer.nvim compatibility:
json
{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "process",
      "label": "dev server",
      "command": "npm",
      "args": ["run", "dev"],
      "isBackground": true,
      "presentation": {
        "revealProblems": "onProblem"
      },
      "problemMatcher": {
        "pattern": {
          "regexp": "^error:.*",
          "file": 1,
          "line": 2
        },
        "background": {
          "activeOnStart": false,
          "beginsPattern": ".*Rebuilding.*",
          "endsPattern": ".*listening.*"
        }
      }
    }
  ]
}
NOTE: The development server does not start automatically when bypassing Tauri CLI. Use overseer.nvim or start it manually.

创建
.vscode/tasks.json
以兼容overseer.nvim:
json
{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "process",
      "label": "dev server",
      "command": "npm",
      "args": ["run", "dev"],
      "isBackground": true,
      "presentation": {
        "revealProblems": "onProblem"
      },
      "problemMatcher": {
        "pattern": {
          "regexp": "^error:.*",
          "file": 1,
          "line": 2
        },
        "background": {
          "activeOnStart": false,
          "beginsPattern": ".*Rebuilding.*",
          "endsPattern": ".*listening.*"
        }
      }
    }
  ]
}
注意:绕过Tauri CLI时,开发服务器不会自动启动,请使用overseer.nvim或手动启动。

CrabNebula DevTools

CrabNebula DevTools

CrabNebula DevTools provides real-time application instrumentation including log inspection, performance monitoring, and Tauri event/command analysis.
CrabNebula DevTools提供实时应用程序检测功能,包括日志检查、性能监控以及Tauri事件/命令分析。

Features

功能

  • Inspect log events (including dependency logs)
  • Monitor command execution performance
  • Analyze Tauri events with payloads and responses
  • Real-time visualization
  • 检查日志事件(包括依赖项日志)
  • 监控命令执行性能
  • 分析带有负载和响应的Tauri事件
  • 实时可视化

Installation

安装

bash
cargo add tauri-plugin-devtools@2.0.0
bash
cargo add tauri-plugin-devtools@2.0.0

Setup

设置

Initialize DevTools as early as possible in
src-tauri/src/main.rs
:
rust
fn main() {
    // Initialize DevTools only in debug builds
    #[cfg(debug_assertions)]
    let devtools = tauri_plugin_devtools::init();

    let mut builder = tauri::Builder::default();

    #[cfg(debug_assertions)]
    {
        builder = builder.plugin(devtools);
    }

    builder
        .run(tauri::generate_context!())
        .expect("error while running tauri application")
}
src-tauri/src/main.rs
中尽早初始化DevTools:
rust
fn main() {
    // Initialize DevTools only in debug builds
    #[cfg(debug_assertions)]
    let devtools = tauri_plugin_devtools::init();

    let mut builder = tauri::Builder::default();

    #[cfg(debug_assertions)]
    {
        builder = builder.plugin(devtools);
    }

    builder
        .run(tauri::generate_context!())
        .expect("error while running tauri application")
}

Usage

使用方法

When running
tauri dev
, DevTools automatically opens a web-based interface showing:
  • Application logs with filtering
  • IPC command calls with timing
  • Event payloads and responses
  • Performance spans
For full documentation, see CrabNebula DevTools docs.

运行
tauri dev
时,DevTools会自动打开一个基于Web的界面,展示:
  • 可过滤的应用程序日志
  • 带有计时信息的IPC命令调用
  • 事件负载和响应
  • 性能跨度
完整文档请参阅CrabNebula DevTools文档

Quick Reference

快速参考

TaskCommand/Action
Enable backtraces
RUST_BACKTRACE=1 tauri dev
Open WebView DevTools
Ctrl+Shift+i
/
Cmd+Option+i
Debug build
tauri build --debug
Add DevTools plugin
cargo add tauri-plugin-devtools@2.0.0
任务命令/操作
启用回溯功能
RUST_BACKTRACE=1 tauri dev
打开WebView DevTools
Ctrl+Shift+i
/
Cmd+Option+i
创建调试构建
tauri build --debug
添加DevTools插件
cargo add tauri-plugin-devtools@2.0.0

IDE Comparison

IDE对比

FeatureVS CodeRustRoverNeovim
Extension/Pluginvscode-lldbBuilt-innvim-dap + codelldb
Windows AltcppvsdbgBuilt-incodelldb
Task Runnertasks.jsonRun configsoverseer.nvim
Setup ComplexityMediumLowHigh
特性VS CodeRustRoverNeovim
扩展/插件vscode-lldb内置nvim-dap + codelldb
Windows替代方案cppvsdbg内置codelldb
任务运行器tasks.json运行配置overseer.nvim
设置复杂度中等

Common Issues

常见问题

  1. Breakpoints not hit: Ensure
    --no-default-features
    is set when building
  2. Dev server not starting: Configure
    preLaunchTask
    or start manually
  3. App not loading frontend: Dev server must be running before Tauri app starts
  4. Windows enum display issues: Use cppvsdbg instead of LLDB
  1. 断点未命中:确保构建时设置了
    --no-default-features
  2. 开发服务器未启动:配置
    preLaunchTask
    或手动启动
  3. 应用未加载前端:必须在Tauri应用启动前运行开发服务器
  4. Windows枚举显示问题:使用cppvsdbg替代LLDB