Git - Ignore Node_Modules Folder Everywhere

I have a project containing multiple other projects :

  • Main project
    • Mini project 1
    • Mini project 2

All containing node_modules folder. I want git to ignore the folder no matter where it is starting from the root folder. Something like this to add in .gitignore :

*node_modules/*

18 Answers

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.

5

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.

6

Edit - (Before 09-04-2022)

In a new monorepo setup I found just using this

node_modules

solved it to ignore all the node_modules in the subdirectory, note there is no slash before or after which means recursive.

Reference

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.