Skip to content

将 Visual Studio Code (VS Code) 的现有项目关联到 GitHub,可以通过以下步骤完成:

  1. 确保必要工具已安装

    1. Git 工具 确保你的电脑已经安装了 Git。如果没有,先安装: • MacOS:

brew install git

•	Debian/Ubuntu:

sudo apt install git

•	Windows: 从 Git 官方网站下载安装。

2.	VS Code Git 插件

在 VS Code 的扩展市场中,搜索并安装 GitHub 或 Git 插件(一般默认已安装)。 3. GitHub 账号 确保你已有 GitHub 账号,并配置好 SSH 密钥或 HTTPS 访问方式。

  1. 初始化 Git 仓库

    1. 打开现有项目目录: • 在 VS Code 的左侧导航中,点击 “文件” -> “打开文件夹” -> 选择你的项目文件夹。
    2. 打开终端(在 VS Code 中 Ctrl + ~ 快捷键可调出终端),初始化 Git 仓库:

git init

•	这将在项目文件夹中创建一个 .git 目录。

3.	添加文件到暂存区并提交:

git add . git commit -m "Initial commit"

  1. 创建 GitHub 仓库

    1. 登录到你的 GitHub 账号,点击右上角的 “+” 按钮,选择 “New Repository”。
    2. 填写仓库信息: • Repository Name:填写项目名称。 • Visibility:选择 Public 或 Private。 • 不要勾选 “Initialize this repository with a README”,因为已有项目会覆盖此内容。
    3. 点击 Create Repository。
  2. 关联本地仓库到 GitHub

    1. 在 GitHub 仓库页面,复制远程仓库的地址(SSH 或 HTTPS)。 • 例: • SSH: [email protected]:username/repository.git • HTTPS: https://github.com/username/repository.git
    2. 在 VS Code 的终端中运行以下命令,将远程仓库地址添加到本地项目:

git remote add origin <远程仓库地址>

例如:

git remote add origin https://github.com/username/repository.git

3.	推送本地代码到 GitHub:

git branch -M main git push -u origin main

  1. 验证关联成功

    1. 打开 GitHub 仓库页面,刷新后可以看到项目文件已成功推送到 GitHub。
    2. 在 VS Code 中,任何文件更改后,可以通过以下命令推送到 GitHub:

git add . git commit -m "Your commit message" git push

  1. VS Code Git 集成(可选)

    1. 在 VS Code 左侧导航栏点击 Source Control 图标(通常是 Git 图标)。
    2. 可以直接在界面中完成提交(Commit)、拉取(Pull)和推送(Push)操作,而无需每次使用命令行。

完成这些步骤后,现有项目就成功关联到 GitHub 并可以正常同步代码了。如果遇到任何问题,可以告诉我!