Monorepo with Git Submodules
What you'll build
A main repository that includes a shared library as a submodule, with scripts to initialize, update, and sync submodules across the team.
Goals
- Add a submodule with git submodule add
- Clone a repo with submodules using --recursive
- Update a submodule to a newer commit
- Document the workflow for the team
Prerequisites
- Basic Git workflow
- Repository hosting (GitHub/GitLab)
- Understanding of project dependencies
Steps
- 1
Design the repo structure
Plan the layout: a shared-lib repo (standalone), and a main app repo that includes shared-lib as a submodule. Document which files live where. Acceptance: the structure is clear before you create anything.
Hint
Submodules pin a specific commit of the sub-repo, so the main repo always builds against a known version.
- 2
Create and add the submodule
Create the shared-lib repo on your host, then in the main repo run git submodule add <url> shared-lib. Commit the new .gitmodules file. Acceptance: the submodule appears as a subdirectory.
Hint
The .gitmodules file records the submodule URL and path — commit it so teammates get the reference.
- 3
Clone with submodules
Clone the main repo fresh with git clone --recursive <url>. Without --recursive, the submodule directory is empty. Acceptance: a fresh clone has the submodule content.
Hint
For an existing clone, run git submodule update --init --recursive to fetch submodule content.
- 4
Update the submodule
Make a new commit in the shared-lib repo (inside the submodule directory), push it, then in the main repo stage the submodule pointer with git add shared-lib and commit. Acceptance: the main repo now pins the new submodule commit.
Hint
Treat the submodule as a file that stores a commit hash — updating it means changing that hash.
- 5
Document the team workflow
Write a README section covering: how to clone (with --recursive), how to update submodules (git submodule update --remote), and common pitfalls (detached HEAD, forgetting to commit the pointer). Acceptance: a new teammate can follow it.
Hint
The most common pitfall is forgetting to commit the updated submodule pointer after pulling new submodule changes.
Try it yourself
What you learned
You managed a multi-repo setup with submodules — a common pattern for sharing code across teams, with trade-offs you now understand (complexity vs. isolation).
Related Resources
Related Lessons
- Branching
Submodules pin specific commits across repos.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.