🧩 一、常见写法及含义详解

写法 含义 示例说明
*.log 忽略所有目录下以 .log 结尾的文件 app.log, logs/error.log 都会被忽略
filename 忽略所有目录下名为 filename 的文件 .npmrc, package-lock.json
/filename 只忽略项目根目录下的 filename 文件 不会忽略子目录里的 .npmrc
dirname/ 忽略名为 dirname 的目录(包括其内容) /node_modules/ 会忽略整个 node_modules 目录
**/filename 忽略任意层级子目录下的 filename 文件 比如 src/utils/.npmrc 也会被忽略
dir/**/*.txt 忽略某个目录及其子目录下的所有 .txt 文件 比如 dir/logs/a.txt 被忽略

🔍 二、具体举例说明

假设你的项目结构如下:

my-project/
├── .npmrc
├── package.json
├── hvigorfile.ts
├── .gitignore
├── src/
│   └── .npmrc        ← 子目录也有一个 .npmrc
└── node_modules/

情况 1️⃣:只写 .npmrc

.npmrc
  • ✅ 效果:Git 会忽略 所有位置的 .npmrc 文件
  • ❌ 包括根目录和 src/ 等子目录中的 .npmrc

情况 2️⃣:写成 /.npmrc

/.npmrc
  • ✅ 效果:只会忽略 项目根目录下的 .npmrc
  • ❌ 不会忽略子目录中的 .npmrc

情况 3️⃣:写成 **/.npmrc

**/.npmrc
  • ✅ 效果:忽略 所有子目录下的 .npmrc 文件
  • ⚠️ 常用于确保不会遗漏任何地方的配置文件

✅ 三、总结表格

写法 是否忽略根目录文件 是否忽略子目录文件 推荐用法
.npmrc ✅ 推荐,通用性强
/.npmrc ❌ 不推荐,容易漏掉子目录
**/.npmrc ✅ 和 .npmrc 效果一样,更显式

💡 四、建议

你现在 .gitignore 中已经写了这些:

/node_modules
/oh_modules
/local.properties
/.idea
**/build
/.hvigor
...
  • /node_modules → 只忽略根目录下的 node_modules,不包括子模块中的
  • 如果你想忽略所有位置的 node_modules,应写成:
**/node_modules

同理:

原写法 更通用写法 说明
/node_modules **/node_modules 忽略所有位置的 node_modules
/oh_modules **/oh_modules 忽略所有位置的 oh_modules
/.hvigor **/.hvigor 忽略所有位置的 .hvigor 目录

✅ 最终建议 .gitignore(更全面)

# 忽略依赖目录
**/node_modules
**/oh_modules

# 忽略构建输出
**/build
**/.hvigor

# 忽略配置与敏感文件
.local.properties
.npmrc

# 忽略 IDE 文件
**/.idea
**/.appanalyzer
**/.clangd
**/.clang-format
**/.clang-tidy

# 忽略临时测试文件
**/.test

# 忽略编译缓存
.cxx
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐