Exclude node_modules folder with .gitignore file

Learn about .gitignore file and how to use it to exclude node_modules from Git tracking

Posted on April 11, 2021


The node_modules/ folder is the folder where all packages required by your JavaScript project are downloaded and installed. This folder is commonly excluded from a remote repository because it has a large size and you shouldn’t add code that you didn’t write to the repository.

Rather than including the node_modules/ folder, you should have the packages required by your project listed in package.json file and ignore the node_modules/ folder using the .gitignore file.

A .gitignore file is a plain text file where you can write a list of patterns for files or folders that Git must not track from your project. It’s commonly used to exclude auto-generated files in your project. To ignore the node_modules/ folder, you simply need to write the folder name inside .gitignore file:

node_modules/

And with that, your node_modules/ folder will be ignored by Git.

If you already have the node_modules/ folder committed and tracked by Git, you can make Git forget about the folder by removing it from Git cache with the following command:

git rm -r --cached .

The command above will remove all tracked files from Git cache, so you need to add them back using git add . where the dot (.) symbol will add all files in the folder, but still exclude those in the .gitignore file.

Next, you just need to commit the changes and push them into your remote repository. Here’s the full git command:

git rm -r --cached .
git add .
git commit -m "Remove node_modules folder"
git push

Feel free to modify the commands above as you require 😉

Related articles:

Level up your programming skills

I'm sending out an email once every Wednesday with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.