Git submodule is a powerful feature that allows us to import external repositories into projects. This modular approach enhances code organization, facilitates collaboration and simplifies dependency management.
Open a terminal window and navigate to the root directory of your existing Git project. This is where you want to add the submodule.
cd path/to/your/project
Use the git submodule add
command to add a submodule to your project. Replace submodule_url with the URL of the Git repository you want to add.
git submodule add submodule_url
For example
git submodule add https://github.com/example/repo.git
After adding the submodule, commit the changes to your main project. This records the submodule's information in your project's version history.
git commit -m "Add submodule: repo"
If you are sharing your project with others, or if you are cloning it onto another machine, use the --recursive
flag to initialize and update the submodules.
git clone --recursive https://github.com/yourusername/yourproject.git
If you've already cloned the project without the --recursive flag, you can initialize the submodules using:
git submodule update --init --recursive
When you make changes within the submodule, navigate into the submodule directory, make your changes, commit, and push as you would in a regular Git repository.
cd path/to/submodule
# Make changes
git add .
git commit -m "Update submodule"
git push origin main
Back in the main project, commit the submodule's new commit reference:
cd path/to/your/project
git add .
git commit -m "Update submodule to latest commit"
git push origin main