How to ignore the node_modules folder in Git?
To ignore the node_modules folder in Git, create a .gitignore file with this entry:
In this article, we will go over the node_modules folder, whether you should ignore it or include it, and how to remove this folder from Git.
Let's get to it 😎.
What is the node_modules folder?
Node_modules, a folder created by npm or yarn, contains all the packages installed locally from packages.json.
This folder contains all the project downloaded dependencies.
Reinstalling an existing package will not require a download from the Internet because node_modules also acts as a cache. In npm, if you want to reinstall all the packages freshly, you need to clear the npm cache.
Should you commit the node_modules folder in Git?
No, you should NOT commit the node_modules folder in Git.
Here are all the reasons why you shouldn't commit it:
- The node_modules folder has a massive size (up to Gigabytes).
- It is easy to recreate the node_modules folder via packages.json.
- It is unnecessary to commit code that you didn't write (in most cases).
How to ignore node_modules in Git?
To ignore the node_modules folder, you must create a .gitignore file.
Then write the folder name to ignore it.
Sometimes, however, a developer might commit the node_modules folder by mistake. Luckily the git rm command exists to fix this mistake.
How to remove node_modules from Git?
To remove the node_modules folder from Git, follow those simple steps:
1. Create a .gitignore file with this entry.
2. Remove the node_modules folder from the Git index using the git rm cached command.
git rm -r --cached node_modules
3. Commit the changes.
git commit -am "removed node_modules folder"
4. Push the changes to the remote.
git push origin master
As you can see, the process of ignoring the node_modules folder from Git is very straightforward.
You should do it to save space and hassles when switching branches.
Here are some other related tutorials that I wrote: