git submodule子模块的使用


前言

git submodule 是git提供的一个用于管理代码复用的解决方案,相比使用npm包,submodule在使用上更加灵活,特别是对于业务代码的复用。


一、官方参考文档

git submodule 子模块

二、使用步骤

现有https://github.com/demo/test.git项目,引用component-xcx子模块,示例:

1.添加submodule

# src/component-xcx 表示要把C模块添加到哪个目录
git submodule init
git submodule add https://github.com/demo/component-xcx.git src/component-xcx

2.修改模块内容

  1. src/component-xcx 目录下,完成component-xcx模块的修改,并使用 git commit git push 命令提交代码到component-xcx仓库。

  2. 在test项目,执行 git commit -am "feat: update submodule" git push 把子模块的引用更新到最新。

  3. 如果submodule有更新,当我们pull代码时,vscode会提示会有更新,这时候只要执行 git submodule update --remote 就可以更新到最新版。(谨慎操作:如撤销此修改,并推送代码,会将该分支的子模块引用记录还原)
    在这里插入图片描述

  4. 跨项目使用时,只会在子仓库那里显示,可以设置git config,控制在git pull让项目更新
    在这里插入图片描述

    #当前仓库设置(亲测,没啥用)
    git config --local submodule.recurse true
    #全局设置(未测试)
    git config --global submodule.recurse true
    

    自用方案:将更新命令加在package.json中

    "start": "npm run update &&  rm -rf ./dist && npm install && cross-env NODE_ENV=development gulp",
    "update": "git pull && git submodule update --remote",
    

3.clone带有子模块的项目

# 和普通项目一样,正常clone
git clone https://github.com/demo/test.git

# clone结束后,子模块是空的,这时候需要一次初始化
git submodule init && git submodule update

三、删除submodule

1. 移除 .gitmodules

# 移除 .gitmodules
rm -rf  .gitmodules

2.移除子模块,并清除git缓存

# 移除子模块,并清除git缓存
git rm -rf src/component-xcx

3.删除git config中submodule配置

cat .git/config
vi .git/config

在这里插入图片描述

4.删除模块下的子模块目录

删除模块下的子模块目录,每个子模块对应一个目录,注意只删除对应的子模块目录即可
如果不执行该命令,再添加相同名字的子模块时会冲突,src/component-xcx为模块名称

    #rm -rf .git/modules/*
    rm -rf .git/modules/src/component-xcx

完成以上操作后,git commit修改,然后就可以重新添加submodule了

四、更换子模块仓库地址

1.修改.gitmodules文件

在这里插入图片描述

2.执行git submodule sync同步命令

在这里插入图片描述

3.初始化/更新子仓库

#初始化仓库及更新
git submodule init && git submodule update

完成!!!
注意:git submodule sync 命令很重要!不执行回影响子模块的引用


总结

正常使用git submodule,这些步骤已够用。


版权声明:本文为qq_38253549原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。