VS Code 可直接作为 Git 的 difftool 和 mergetool 使用,需先启用命令行工具 code,再配置 git config --global diff.tool vscode 与 mergetool vscode,并设置对应 cmd 命令及 --wait 参数。

VS Code 可以直接作为 Git 的 mergetool 和 difftool 使用,无需额外插件,只需正确配置即可。关键在于启用 VS Code 的命令行工具(code),并设置 Git 的对应选项。
1. 确保 VS Code 命令行工具可用
这是前提。如果在终端中输入 code --version 报“command not found”,说明未启用 CLI 工具。
- 打开 VS Code,按
Cmd+Shift+P(macOS)或Ctrl+Shift+P(Windows/Linux)调出命令面板 - 输入
Shell Command: Install 'code' command in PATH并回车执行 - 重启终端,验证:
code --version应能输出版本号
2. 配置 Git 使用 VS Code 作为 difftool
用于查看文件差异(如 git diff 或 git difftool)。
- 运行以下命令全局启用:
git config --global diff.tool vscode
git config --global difftool.vscode.cmd 'code --wait --diff "$LOCAL" "$REMOTE"'
-
--wait:让 Git 等待你关闭比较窗口后再继续,避免终端卡住 -
--diff:启动内建的左右对比模式 -
"$LOCAL" "$REMOTE":Git 自动传入的临时文件路径(注意加引号防空格)
3. 配置 Git 使用 VS Code 作为 mergetool
用于解决合并冲突(如 git mergetool)。
- 运行以下命令:
git config --global merge.tool vscode
git config --global mergetool.vscode.cmd 'code --wait "$MERGED"'
-
"$MERGED"是 Git 提供的冲突解决后保存的目标文件路径 - VS Code 会自动识别冲突标记(
,======,>>>>>),并提供“接受当前更改/入站更改/两者”等操作按钮 - 保存文件并关闭编辑器,Git 即认为该文件已解决
4. (可选)设为默认,跳过提示
每次运行 git difftool 或 git mergetool 时,默认会询问是否启动工具。可跳过:
git config --global difftool.prompt falsegit config --global mergetool.prompt false
基本上就这些。配置完成后,git difftool HEAD~1 file.js 会打开对比视图,git mergetool 会逐个加载冲突文件。不复杂但容易忽略 CLI 工具启用这一步。










