Managing Shared Code Across Repositories with Subtree
Use git subtree to embed and synchronize shared libraries or components across multiple repositories without submodule complexity.
Prerequisites
- -Git installed
- -Two or more repositories (a main project and a shared library)
- -Push access to both repositories
Steps
Add a remote for the shared library
Add the shared library repository as a named remote so you can reference it in subtree commands.
Add the subtree to your project
Pull the shared library into the lib/shared-ui directory. The --squash flag collapses the library's history into a single merge commit.
Use --squash to keep your project history clean. Without it, the entire library history is merged into your project.
The prefix directory must not already exist. Git will create it and populate it with the library contents.
Pull updates from the shared library
Fetch and merge the latest changes from the shared library into your project's subtree directory.
Make local changes to the subtree
You can modify subtree files directly in your project and commit them normally. These changes live in your project's history.
Push local changes back to the shared library
Extract commits that touched the subtree directory and push them to the shared library repository on a new branch.
Push to a feature branch on the shared library and create a pull request, rather than pushing directly to main.
Split subtree into a standalone branch
Extract the subtree history into a standalone branch. This is useful for initially creating a shared library from code that started in a monorepo.
Full Script
FAQ
Discussion
Loading comments...