Skip to content

Gitignore 设置项目

入门 约 10 分钟

你将构建什么

仓库使用 comprehensive .gitignore 那个排除 node_modules, 环境 files, 构建输出, and OS-特定 files. 你将 验证 ignore 规则工作通过检查 git 状态.

学习目标

  • 创建 .gitignore file 使用常见模式
  • 理解 wildcard and directory-特定模式
  • 验证那个 ignored files 做不 appear in git 状态
  • 提交 .gitignore 所以它 是 shared 使用 team

前置要求

  • Git 安装 and 基础 init/添加/提交 workflow

步骤

  1. 1

    设置项目

    创建新 仓库 and 添加一些 files 那个应该是 ignored: node_modules folder, .环境 file, and 构建 directory.

    代码
    mkdir gitignore-project
    cd gitignore-project
    git init
    mkdir node_modules build
    echo "secret" > .env
    echo "{}" > node_modules/lib.json
    echo "compiled" > build/app.js
    echo "console.log('hi')" > index.js

    预期结果

    仓库使用索引.js (到 keep) and node_modules, .环境, 构建 (到 ignore).

  2. 2

    创建 .gitignore file

    编写 .gitignore 使用模式 for dependencies, secrets, 构建输出, and OS files. 每个行 是 glob 模式.

    代码
    cat > .gitignore << 'EOF'
    # Dependencies
    node_modules/
    
    # Environment variables
    .env
    *.env
    
    # Build output
    build/
    dist/
    
    # OS files
    .DS_Store
    Thumbs.db
    
    # Logs
    *.log
    EOF

    预期结果

    .gitignore file 使用 ignore 模式 for 常见 file 类型.

  3. 3

    验证 ignore 规则

    运行 git 状态到 确认那个 node_modules, .环境, and 构建/ 做不 appear. 仅索引.js and .gitignore 应该 show as untracked.

    代码
    git status

    预期结果

    仅索引.js and .gitignore appear as untracked files.

  4. 4

    提交 .gitignore

    Stage and 提交 .gitignore and 索引.js. .gitignore 它自己应该是 committed 所以所有 team 成员 share 相同 ignore 规则.

    代码
    git add .gitignore index.js
    git commit -m "Add .gitignore and entry point"

    预期结果

    Two files committed; ignored files 是排除从 仓库.

  5. 5

    验证仓库状态

    使用 git status 和 git log 确认当前仓库状态干净、提交历史符合预期。在执行任何破坏性操作前,先看清当前状态是 Git 的最佳实践。

    代码
    git status
    # Should show: nothing to commit, working tree clean
    
    git log --oneline -5
    # Review the last 5 commits to confirm history
    git branch -v
    # List branches with last commit info

    预期结果

    git status 显示工作树干净;git log 显示预期的提交历史。

自己动手试试

你学到了什么

你创建 practical .gitignore 使用模式 for dependencies, secrets, 构建输出, and OS files. 好 .gitignore 是首先行 的 defense 针对 committing sensitive 数据 and junk files.

相关资源

相关课程

相关工具

相关速查表

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题