Git Submodules
A Git Submodule allows you to keep a Git repository as a subdirectory of another Git repository. This lets you clone another repository into your project and keep your commits separate.
When to Use Git Submodules?
Git submodules provide an excellent solution when you’re dealing with multiple repositories under the same project. They are especially convenient for full-stack projects where the frontend, backend, and mobile apps are each housed in separate repositories.
Basic Usage
If you have an existing project and want to incorporate it into your project, navigate to your project’s repository and use the git submodule add command followed by your project’s repository URL.
cd my-projectgit submodule add https://github.com/username/other-projectThis command does two things:
- It clones the subproject repository into your project. Your project now has a copy of that entire subproject.
- It makes a special type of commit that tracks the exact commit of the submodule repository.
After adding a submodule, a .gitmodule file is created in the root direction, which keeps track of the mapping between the project’s URL and the local subdirectory you’ve introduced.
cat .gitmodulesTo clone a project with submodules, you need to use two commands: git clone and then git submodule init.
git clone https://github.com/username/my-projectcd my-projectgit submodule initgit submodule updateOr you can use the —recurse-submodules flag with the clone command.
git clone --recurse-submodules https://github.com/username/my-project