How to ignore the node_modules folder in Git?

Tim Mouskhelichvili
Tim Mouskhelichvili
• 2 minutes to read

The node_modules folder contains all the saved JavaScript dependencies of a project. Since this folder often has a massive size, developers typically do not commit it inside the Git repository.

To ignore the node_modules folder in Git, create a .gitignore file with this entry:

.gitignore filenode_modules

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.

.gitignore filenode_modules

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.

.gitignore filenode_modules

2. Remove the node_modules folder from the Git index using the git rm cached command.

bashgit rm -r --cached node_modules

3. Commit the changes.

bashgit commit -am "removed node_modules folder"

4. Push the changes to the remote.

bashgit push origin master

Final thoughts

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.

git ignore node_modules

Here are some other related tutorials that I wrote:

Comments (1)
Reply to:
ES March 07, 2023 10:38AM
thanks. came pretty handy in a tight spot
REPLY