Git - Ignore node_modules folder everywhere

Add node_modules/ or node_modules to the .gitignore file to ignore all directories called node_modules in the current folder and any subfolders like the below image.

example


Use the universal one-liner in terminal in the project directory:

touch .gitignore && echo "node_modules/" >> .gitignore && git rm -r --cached node_modules ; git status

It works no matter if you've created a .gitignore or not, no matter if you've added node_modules to git tracking or not.

Then commit and push the .gitignore changes.

Explanation

touch will generate the .gitignore file if it doesn't already exist.

echo and >> will append node_modules/ at the end of .gitignore, causing the node_modules folder and all subfolders to be ignored.

git rm -r --cached removes the node_modules folder from git control if it was added before. Otherwise, this will show a warning pathspec 'node_modules' did not match any files, which has no side effects and you can safely ignore. The flags cause the removal to be recursive and include the cache.

git status displays the new changes. A change to .gitignore will appear, while node_modules will not appear as it is no longer being tracked by git.


**/node_modules

** is used for a recursive call in the whole project

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.

Why this approach is better than node_modules/

The ** acts as a recursive pattern. It is useful in monorepo projects where you have node_modules in sub directories. ** will search for all the node_modules inside the directory & ignore them.

Reference