Git ignore node modules - Simple Solution and Common Gotchas
Add the following line to your .gitignore file
node_modulesIt will match the node_modules directory anywhere in your git repository.
Don't forget to add .gitignore to git too:
git add .gitignoreGotcha #1 - No .gitignore file
If you don't have a .gitignore file, simply create an empty text file in the root of your git repository and add the single line containing node_modules.
You can find the reference and examples for .gitignore at Git - gitignore Documentation (git-scm.com).
Gotcha #2 - node_modules already committed
If you've already committed node_modules , you'll need to first remove the directory from git index. Otherwise, adding it to .gitignore won't make any difference.
To remove node_modules from git, but leave it in the working tree use git rm command (reference):
git rm -r --cached node_modulesWhat does this do?
-r flag makes sure the command is applied recursively to all files and subdirectories in the node_modules directory
--cached makes sure we remove the files only from git index and keep them in the working directory. According to the reference: Use this option to unstage and remove paths only from the index. Working tree files, whether modified or not, will be left alone.
Related articles
gitroot – a Simple Command to Navigate to the Root of a Git Repo