
Module 7 Lesson 2: Adding submodules to a repository
Start building your architecture. Learn the 'git submodule add' command and understand how the .gitmodules file tracks your external dependencies.
Module 7 Lesson 2: Adding submodules to a repository
Ready to add your first dependency? Adding a submodule is simple, but Git does several things behind the scenes that you need to be aware of.
In this lesson, we learn the git submodule add command and investigate the metadata files it generates.
1. The Add Command
To add a remote repository as a submodule into a specific folder in your project:
# git submodule add <url> <path>
git submodule add https://github.com/example/lib-ui.git libs/ui
What happens?
- Git clones the repository into the
libs/uifolder. - Git adds the directory to your staged changes.
- Git creates (or updates) a file called
.gitmodules.
2. The .gitmodules File
This is a configuration file that tracks your submodules. It belongs in the root of your project and must be committed to the repository.
It looks something like this:
[submodule "libs/ui"]
path = libs/ui
url = https://github.com/example/lib-ui.git
Why is this file important?
When your teammates clone your project, Git uses this file to know where to go to find the submodule's code.
3. How Git Tracks the Code
Crucially, Git does not track the files inside the submodule.
Instead, it tracks the Commit ID that the submodule is currently "checked out" to. In your git status or git diff, you will see something like:
+Subproject commit 1a2b3c4d...
This means "My project is currently using version 1a2b3c4d of the UI library."
4. Committing the Submodule
After running the add command, you must commit the changes to your parent repository:
git add .gitmodules libs/ui
git commit -m "Add UI Library as a submodule"
graph LR
User["User"] -- "git submodule add" --> Git["Git Logic"]
Git --> Disk["Clone to Subfolder"]
Git --> Meta[".gitmodules Config"]
Git --> Stage["Stage Commit ID"]
Lesson Exercise
Goal: Architect a subproject.
- Create a dummy repository on GitHub (or use a small existing one) to act as your "Library."
- In your
git-practicefolder, rungit submodule add <URL> external/mylib. - Check your folder structure. Does
external/mylibcontain the code from the other repo? - Open the
.gitmodulesfile in a text editor. - Run
git status. Notice that Git sees both the.gitmodulesfile and the new folder as staged changes. - Commit the changes.
Observation: You'll see that your project now has a "project within a project."
Summary
In this lesson, we established:
git submodule addis the command to create a new dependency.- The
.gitmodulesfile stores the mapping between paths and URLs. - The parent repo only tracks the commit ID of the submodule, not its actual files.
- You must commit the submodule addition just like any other change.
Next Lesson: If you share your project, your teammates won't get the submodule code by default. We’ll learn Lesson 3: Cloning repositories with submodules.