How to Add a GIT Submodule to Your Repository

git logo

Adding a Git submodule to your repository is a straightforward process. A submodule allows you to include and track a repository inside another Git repository, making it easier to manage dependencies.

Here’s how to add a submodule:

  1. Navigate to Your Repository:
    Open a terminal, command prompt, or Git Bash and navigate to your main repository’s directory:

    cd /path/to/your/main-repo
    
  2. Add the Submodule:
    Use the git submodule add command, followed by the repository URL of the submodule and the path where you want to store it:

    git submodule add https://github.com/example/example-repo.git path/to/submodule
    
    • Replace https://github.com/example/example-repo.git with the URL of the repository you want to add as a submodule.
    • Replace path/to/submodule with the directory path where you want to store the submodule. This path is relative to your main repository’s root. If you omit this, the submodule will be added to a directory named after the repository.
  3. Initialize and Clone the Submodule:
    After adding a submodule, Git automatically initializes and clones it into the specified directory. If you ever need to initialize and clone submodules manually, you can use:

    git submodule update --init --recursive
    
  4. Commit the Change:
    Adding a submodule modifies the .gitmodules file and the index of your repository. You should commit these changes:

    git commit -am "Add submodule example-repo"
    
  5. Cloning a Repository with Submodules:
    If you are cloning a repository that already contains submodules, remember to include --recurse-submodules:

    git clone --recurse-submodules https://github.com/your/repo.git
    

    Alternatively, after cloning, you can initialize and update the submodules:

    git submodule update --init --recursive
    

These steps should help you successfully add and manage submodules in your Git projects.