





















Git Submodule 允许在一个 Git 仓库(主项目)中嵌入另一个 Git 仓库(子模块),主项目仅记录子模块的 URL 和特定 commit ID,而非其实际代码。这使得多个项目可以共享独立维护的代码库,同时保持版本可控。
适用场景:
命令示例:
$ git submodule add <子仓库url> <目标路径path>
示例:git submodule add https://github.com/example/lib.git libs/lib
执行后会:
💡 若省略目标路径,默认使用仓库名作为子模块目录名。
此时报了一个警告:warning: in the working copy of '.gitmodules', LF will be replaced by CRLF the next time Git touches it
这是因为在文本处理中,Windows 平台中使用 CR/LF(回车/换行)作为换行符,Linux 平台中仅使用 LF(换行)作为换行符,这个问题可以通过以下方式解决:
$ git config --global core.autocrlf true
git clone --recurse-submodules <主仓库URL>
git clone <主仓库URL>
cd <主仓库目录>
git submodule init
git submodule update
合并命令:
# 自动初始化并更新
git submodule update --init
进入子模块目录手动更新(适用于开发子模块),在子模块中创建分支并工作(就像在普通Git仓库中一样):
cd <子仓库目录>
git checkout -b feature-branch
# 进行修改
git add .
git commit -m "Made changes in submodule"
git push origin feature-branch # 或其他分支
# 返回主项目并提交子模块的引用变更
cd ..
git add <子仓库目录>
git commit -m "Updated submodule to new version"
git push
从主项目直接更新所有子模块(拉取最新提交):
git submodule update --remote --merge
此命令会:
仅同步到主项目记录的 commit(不拉新):
git submodule update
更新特定子模块:
git submodule update --remote <子仓库目录>
删除 .gitmodules 文件中子模块相关条目:
删除 .git/config 配置项中子模块相关条目
删除 .git/module/ 目录下子模块相关内容
删除子模块目录及源码
根据官方文档,使用卸载子模块命令:
git submodule deinit <子模块路径> # 取消注册(删除 .git/config 中配置)
git rm --cached <子模块路径> # 移除 gitlink 和 .gitmodules 条目
rm -rf .git/modules/<子模块路径> # 清理残留元数据
git commit -m "Removed submodule" # 提交变更
若子模块有未提交更改,需加 -f 参数:git submodule deinit -f <path>,此操作是在 .git/config 配置项中删除了子模块相关条目
子模块的注意事项:
常见问题与注意事项
子模块处于“HEAD detached”状态?
是正常现象,因为子模块被检出到主项目指定的 commit。
若需开发,建议创建分支并切换:
cd <submodule>
git checkout -b dev
权限错误(SSH/HTTPS)?
可在 .gitmodules 中将 HTTPS URL 替换为 SSH 格式(如 git@github.com:user/repo.git),然后运行:
git submodule sync --recursive
git submodule update --init --recursive
git submodule status
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。