How to Ignore node_modules in Git

In most JavaScript or Node.js projects, the node_modules folder contains thousands of dependency files that are automatically installed via npm or yarn. These files do not belong in your Git repository—they can significantly bloat your repo and are unnecessary for collaboration.

In this guide, we’ll show you how to ignore node_modules in Git using a .gitignore file.


✅ Step 1: Add node_modules to .gitignore

The .gitignore file tells Git which files or directories to exclude from version control.

🔹 Create or edit .gitignore:

touch .gitignore

Add the following line:

node_modules/

This line ensures Git ignores the entire node_modules directory at the root of your project.


✅ Step 2: Remove node_modules from Git Tracking (if already committed)

If you’ve already committed node_modules, you’ll need to remove it from the repo while keeping it locally.

Run:

git rm -r --cached node_modules

Then commit the change:

git commit -m "Remove node_modules from version control"

✅ Step 3: Push the Changes to Remote (Optional)

If you’re using GitHub, GitLab, or Bitbucket, push the changes:

git push origin main

Replace main with your branch name if needed.


🧠 Why Ignore node_modules?

  • Size: It can contain thousands of files and hundreds of MB.
  • Platform-Specific Builds: Packages can vary across OSes.
  • Reproducibility: Use package.json and package-lock.json to manage dependencies.

🧰 Bonus Tip: Use a Global .gitignore

To avoid committing node_modules in any repo on your system, set up a global .gitignore.

Create and configure global ignore:

git config --global core.excludesfile ~/.gitignore_global
echo node_modules/ >> ~/.gitignore_global

🚀 Final Thoughts

Ignoring node_modules is a best practice in modern development. Instead of committing these dependencies, share your package.json and package-lock.json so others can install them with:

npm install

or

yarn install
Sharing Is Caring:

Leave a Comment