我有一个项目包含多个其他项目:

主要项目 小项目1 小项目2

所有包含node_modules文件夹。我想要git忽略文件夹,无论它是从根文件夹开始的位置。在.gitignore中添加如下内容:

*node_modules/*

当前回答

编辑-(2022-04-09之前)

在一个新的monorepo设置中,我发现只用这个

node_modules

解决了忽略子目录中所有node_modules的问题,注意前面和后面没有斜杠,这意味着递归。

参考

老路-(2022-04-09之前)

**/node_modules

**用于整个项目中的递归调用

Two consecutive asterisks ** in patterns matched against full pathname may have special meaning: A leading ** followed by a slash means match in all directories. For example, **/foo matches file or directory foo anywhere, the same as pattern foo. **/foo/bar matches file or directory bar anywhere that is directly under directory foo. A trailing /** matches everything inside. For example, abc/** matches all files inside directory abc, relative to the location of the .gitignore file, with infinite depth. A slash followed by two consecutive asterisks then a slash matches zero or more directories. For example, a/\**/b matches a/b, a/x/b, a/x/y/b and so on. Other consecutive asterisks are considered invalid.

为什么这种方法比node_modules/更好

**充当递归模式。它在monorepo项目中很有用,因为你在子目录中有node_modules。**将搜索目录中所有的node_modules,并忽略它们。

参考

其他回答

在项目目录的终端中使用通用的一行程序:

触摸。gitignore && echo "node_modules/" >> .gitignore && git rm -r——缓存的node_modules;git状态

不管你是否创建了.gitignore,不管你是否将node_modules添加到git跟踪中,它都能工作。

然后提交并推送.gitignore更改。

解释

如果它不存在,Touch将生成.gitignore文件。

Echo和>>将在.gitignore的末尾追加node_modules/,导致node_modules文件夹及其所有子文件夹被忽略。

Git rm -r——cached从Git控件中删除node_modules文件夹(如果之前添加过)。否则,这将显示一个警告pathspec 'node_modules'不匹配任何文件,这没有副作用,你可以安全地忽略。标志使删除是递归的,并包括缓存。

Git状态显示了新的更改。将出现.gitignore的更改,而node_modules将不会出现,因为git不再跟踪它。

在.gitignore中添加下面的行将忽略整个存储库中的节点模块。

node_modules

遵循以下步骤-

在项目所在的文件夹上打开git bash,或者打开vs code终端 按

CTRL + `

在终端中写入[echo > .gitignore]或创建文件[。Gitignore]直接进入文件夹 然后将其写入忽略整个存储库中的节点模块

node_modules

或者,尝试忽略来自多个子文件夹的所有node_modules

**node_modules

注意:如果你在输入文件夹或文件的名称时出现拼写错误,它将无法工作。所以,仔细检查拼写

直接通过代码编辑器或命令在根文件夹中创建.gitignore文件

Mac和Linux 触摸.gitignore 对于Windows 回声> .gitignore 打开。gitignore,声明文件夹或文件名称,如/foldername

添加以下行到你的。gitignore

*/node_modules/*

这将忽略当前目录和子目录中的所有node_modules。