# [Git] git submodule 项目形式

## 简介

个人感觉 `git submodule` 是一种相对于 `monorepo` 的多模块项目管理方式

对于一些可能在多个仓库/业务中复用的模块，可以考虑将其拆出来单独放到一个仓库中，通过 `git submodule` 的方式引入

一些通用的非业务代码，例如配置文件、 `proto` 、统一的类型声明文件等，比较适合拆成 `git submodule`

## 用法

参考文档：[https://git-scm.com/book/en/v2/Git-Tools-Submodules](https://git-scm.com/book/en/v2/Git-Tools-Submodules)

### 初次拉取 `git submodule`

使用 `git submodule update --init` 拉取，`git` 会根据 `.gitmodules` 文件将远程仓库拉取为 `submodule`

### 更新 `git submodule`

1. 可以在主仓库中使用 `git pull` ，会自动递归拉取所有的子模块，并将子模块的引用更新到远程仓库的最新引用：
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1749886320275/bec725de-6db4-4b9a-9c9c-d44c71926c3f.png align="center")
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1749886301181/19bbd4ca-a6f7-4300-b87c-9a6559a1d426.png align="center")
    
2. 在主仓库中执行 `git submodule update --remote` ，也会将子模块的引用更新到远程仓库的最新引用
    
3. 如果在执行了 `git submodule update --remote` 后出现了冲突，那么你可能需要 `git submodule update --remote --rebase` 来在 `rebase` 的过程中手动解决冲突（或者用 `merge`）：
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1749887001054/bcf85671-7250-4a3a-96fa-41001dc8de73.png align="center")
    

### 在主仓库中提交 `git submodule` 的变更

当使用了 `git submodule` 后，每次更新仓库的远程引用（通过 `fetch`）时，都会显示 `submodule` 的变更

需要你在主仓库中去将这些子模块都添加到暂存区中，然后提交
