Skip to content

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.

Terminal window
cd my-project
git submodule add https://github.com/username/other-project

This 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.

Terminal window
cat .gitmodules

To clone a project with submodules, you need to use two commands: git clone and then git submodule init.

Terminal window
git clone https://github.com/username/my-project
cd my-project
git submodule init
git submodule update

Or you can use the —recurse-submodules flag with the clone command.

Terminal window
git clone --recurse-submodules https://github.com/username/my-project