Nâng CaoGit iconGit

Git submodules vs git subtrees: tại sao hầu hết teams tránh cả hai?

Git Submodules: link đến commit cụ thể của repo khác, lưu trong .gitmodules.

bash
git submodule add https://github.com/org/shared-lib libs/shared
# .gitmodules lưu URL + path
# Clone cần: git clone --recursive hoặc git submodule update --init

Vấn đề thực tế của submodules:
- git clone không tự clone submodules — newbies hay quên --recursive
- Update submodule: phải cd vào, pull, cd ra, commit .gitmodules update
- Detached HEAD state thường xuyên trong submodule directory
- CI/CD phức tạp hơn
- "Why does the build fail?" → submodule pointer pointing to deleted commit

Git Subtree: copy code vào subdirectory, không có reference to external repo.

bash
git subtree add --prefix libs/shared https://github.com/org/shared-lib main --squash
git subtree pull --prefix libs/shared https://github.com/org/shared-lib main --squash

Vấn đề subtree: merge history phức tạp, git log prefix cần, push changes ngược lại upstream khó.

Tại sao hầu hết teams tránh cả hai:
Như là monorepo tool: npm workspaces, Nx, Turborepo tốt hơn nhiều. Như là dependency: publish package lên npm/private registry. Như là vendor code: copy + commit (vendor) đơn giản và transparent hơn.

Git LFS là giải pháp cho binary assets — tốt hơn submodules cho design files, videos.

Xem toàn bộ Git cùng filter theo level & chủ đề con.

Mở danh sách Git