Добавление и клонирование подмодулей
Изучите команды для добавления нового подмодуля в проект и правильного клонирования репозитория вместе с подмодулями
«Добавление и клонирование подмодулей» — бесплатный урок Git Advanced: Monorepo, Submodules & Workflows на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Git Advanced: Monorepo, Submodules & Workflows, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Git Advanced: Monorepo, Submodules & Workflows содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Add & Clone Git Submodules
Git submodules let you embed one Git repository inside another. This is useful for managing external dependencies like libraries or shared components.
In this lesson, we'll learn how to add a new submodule to your project and how to properly clone a repository that contains submodules.
The `git submodule add` Command
To add a submodule, you use the git submodule add command. This command takes the URL of the external repository and optionally a local path where you want to place it.
- Repository URL: The URL (HTTPS or SSH) of the submodule's Git repository.
- Path: The directory within your main project where the submodule will reside. If omitted, Git uses the repository name.
Add Submodule in Action
Let's say you have a my-project repository and want to include a shared library from https://github.com/example/shared-lib.git.
First, navigate to your main project's directory.
cd my-project
git submodule add https://github.com/example/shared-lib.git lib/shared-libFiles Created by `submodule add`
After running git submodule add, Git does a few things:
- It clones the submodule repository into the specified path (e.g.,
lib/shared-lib). - It adds an entry to a special file called
.gitmodulesin your main repository's root. - It stages the new submodule directory and the
.gitmodulesfile for commit.
Inspecting `.gitmodules`
The .gitmodules file is a configuration file that stores the mapping between the submodule's local path and its remote URL. It's crucial for others to clone your project correctly.
Here's what it might look like for our example:
[submodule "lib/shared-lib"]
path = lib/shared-lib
url = https://github.com/example/shared-lib.gitCommit Your Submodule Change
Adding a submodule is a change to your main repository, so you need to commit it. The commit will record the specific commit hash of the submodule's repository that your main project is currently using.
git status
git commit -m "Add shared-lib as a submodule"Cloning a Parent Repository
When you clone a repository that contains submodules, Git clones the parent repository but doesn't automatically download the submodule content.
The submodule directories will appear empty or contain only a .git file pointing to the submodule's repository.
The Easy Way to Clone All
The most straightforward way to clone a repository and all its submodules is to use the --recurse-submodules flag with git clone.
This command clones the main repository and then automatically initializes and updates all submodules to their correct versions.
git clone --recurse-submodules https://github.com/your/my-project.gitManually Initializing Submodules
If you forget --recurse-submodules during cloning, don't worry! You can initialize and update them manually after cloning the parent repository.
First, navigate into the cloned parent repository.
cd my-project
git submodule initFetching Submodule Content
After initializing, you need to tell Git to fetch the actual content for each submodule. This is done with the git submodule update command.
It fetches the data from the submodule's remote and checks out the specific commit recorded by the parent repository.
cd my-project
git submodule updateCheck Your Submodule Knowledge
You've just cloned a repository named parent-repo which is known to contain a submodule. After cloning with just git clone parent-repo.git, what are the necessary commands to get the submodule's content ready for use?
Recap: Add & Clone Submodules
In this lesson, you learned how to:
- Add a submodule using
git submodule add <url> <path>, which creates a.gitmodulesfile and stages the submodule. - Commit submodule changes to record the specific version of the submodule in the parent repository.
- Clone a repository with submodules using
git clone --recurse-submodulesfor an all-in-one operation. - Manually initialize and update submodules with
git submodule initandgit submodule updateif you cloned without the recurse flag.
Next, we'll explore how to manage and update submodules after they've been added and cloned.
Часто задаваемые вопросы
Урок «Добавление и клонирование подмодулей» бесплатный?
Да — полный текст урока «Добавление и клонирование подмодулей» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Git Advanced: Monorepo, Submodules & Workflows, подпишись на CoddyKit PRO. Курс Git Advanced: Monorepo, Submodules & Workflows содержит 4 уроков всего.
Чему я научусь в уроке «Добавление и клонирование подмодулей»?
Изучите команды для добавления нового подмодуля в проект и правильного клонирования репозитория вместе с подмодулями Ты практикуешь Git Advanced: Monorepo, Submodules & Workflows с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Git Advanced: Monorepo, Submodules & Workflows?
Предыдущий опыт не требуется. Git Advanced: Monorepo, Submodules & Workflows на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Добавление и клонирование подмодулей»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Git Advanced: Monorepo, Submodules & Workflows?
Да. Каждый урок Git Advanced: Monorepo, Submodules & Workflows включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Введение в подмодули Git
- Добавление и клонирование подмодулей
- Обновление и синхронизация подмодулей
- Удаление и деинициализация подмодулей