能否在VS Code中实现文件创建后自动执行git add操作?
git add New Files in VS Code Absolutely! You can replicate that WebStorm-style auto-git add behavior in VS Code—here are two reliable, straightforward ways to make it happen:
Method 1: Use a Dedicated Extension
The easiest route is to use an extension built specifically for git automation. A popular and well-reviewed option is Git Auto Add (similar tools like Git Automator work too). Here's how to set it up:
- Open VS Code's Extensions panel (use
Ctrl+Shift+Xon Windows/Linux,Cmd+Shift+Xon Mac) - Search for "Git Auto Add" and install the top-rated extension from the results
- Once installed, most of these extensions will automatically detect new files you create and run
git add <file-path>in the background immediately. If you need to customize behavior—like excluding certain file types or folders—you can tweak the extension's settings via the VS Code settings menu.
Method 2: Set Up a Custom Task with File Watching
If you'd rather avoid using extensions, you can create a custom VS Code task that watches for new file creations and triggers git add automatically:
- Open the command palette (
Ctrl+Shift+P/Cmd+Shift+P) and select Tasks: Open User Tasks - Replace the default JSON content with this configuration:
{ "version": "2.0.0", "tasks": [ { "label": "Auto Git Add New Files", "type": "shell", "command": "git add ${file}", "runOptions": { "runOn": "folderOpen" }, "problemMatcher": [], "trigger": { "event": "onFileCreate", "filters": [ { "filename": "*", "filetype": "file" } ] } } ] }
- Save the file. Now, any time you create a new file in your git repository, this task will automatically run
git addon it. You can adjust thefilterssection if you want to exclude specific file types (for example, add"exclude": "*.log"to skip log files).
A quick heads-up: Make sure VS Code has your git environment properly configured (you've initialized a repository and set up your credentials) for either method to work smoothly.
内容的提问来源于stack exchange,提问作者ZeFifi

