方法一:使用 .gitignore 文件(推荐)
gitignore 是 git - ignore(忽略) 的意思,这是最标准的方法,适用于大多数情况。
-
创建或编辑 .gitignore 文件:
# 如果还没有 .gitignore 文件
touch .gitignore #linux环境下
#Windows环境下,直接右键新建名为 .gitignore 的文件
-
在 .gitignore 中添加要排除的文件夹:
# 排除单个文件夹
folder_to_exclude/
# 或者使用通配符排除所有类似文件夹
*/folder_to_exclude/
# 排除所有名为 node_modules 的文件夹
node_modules/
-
如果文件夹已经被跟踪,需要先将其从 Git 中移除:
# 停止跟踪但保留本地文件
git rm -r --cached folder_to_exclude/
# 提交更改
git add .
git commit -m "停止跟踪 folder_to_exclude 文件夹"
方法二:使用 sparse-checkout(高级用法)
如果你想要一个只包含特定文件夹的稀疏检出:
# 启用 sparse-checkout
git config core.sparseCheckout true
# 指定要包含的文件夹
echo "src/" >> .git/info/sparse-checkout
echo "docs/" >> .git/info/sparse-checkout
# 重新读取工作目录
git read-tree -mu HEAD
方法三:从已提交的文件中移除文件夹
如果文件夹已经被提交到了仓库:
# 从 Git 中移除文件夹但保留本地文件
git rm -r --cached folder_to_exclude/
# 提交更改
git commit -m "移除 folder_to_exclude 文件夹"
# 推送到远程
git push origin main
示例 .gitignore 内容
# 排除 node_modules 文件夹
node_modules/
# 排除日志文件夹
logs/
*.log
# 排除编译输出
dist/
build/
# 排除环境变量文件
.env
.env.local
# 排除 IDE 配置文件
.vscode/
.idea/
注意事项
-
.gitignore 只对未跟踪的文件有效 - 如果文件已经被 Git 跟踪,需要先使用 git rm --cached 移除跟踪。
-
.gitignore 文件本身需要被提交 - 这样其他协作者也会应用相同的忽略规则。
-
使用全局忽略 - 你也可以设置全局忽略规则:
git config --global core.excludesfile ~/.gitignore_global
选择最适合你需求的方法。对于大多数情况,使用 .gitignore 文件是最简单有效的解决方案。