From Chaos to Clarity: Organizing Node Modules with Git One liner

From Chaos to Clarity: Organizing Node Modules with Git One liner

Let’s be real, at some point in our learning journey, we’ve all uploaded our node modules to GitHub. 😅

Whether you are new developer or veteran, sometimes it's quite normal to forget to put your project’s node modules inside .gitignore. In this blog, we will learn a git one-liner which will be helpful in mutiple such situations.

Sometimes we have Mutiple projects inside one project where all of them contain their own node_modules folder.

Or sometimes we have client and server code stored in a same github repository. Like this:

Suppose you want the git to ignore the folder no matter where it is starting from the root folder (here, it’s Main Project). To do so you can this

As seen in the screenshot below, you may ignore any node_modules directories in the current folder and any subfolders by adding node_modules/or node_modules to the .gitignorefile.

Instead of doing this manually, there is a Universal One-liner. Let’s discuss it now to put node_mdules in gitignore file no matter where the node_modules files are located and no matter whether you have the gitignore file or not. This Universal line gets you works either way.

touch .gitignore && echo “node_modules/” >> .gitignore && git rm -r — cached node_modules ; git status

Explanation

  1. Creating gitignore, if not available already

If the .gitignorefile doesn’t already exist, touchwill create it.

2. Adding new node_modules path to gitignore

echo >> will add node_modules/inside the .gitignoreat the end, causing thenode_modulesfolder and all subfolders to be ignored.

3. Remove the pre-existing files, if any

If the node_modulesfolder was previously added to git control, git rm -r --cachedremoves it. If not, a warning that the pathspec 'node_modules' did not match any fileswill appear. This warning has no consequences, so you may safely ignore it.

4. Final display

The new modifications are displayed via git status . A modification to .gitignore will be visible, but node_modules will not be seen because it is no longer monitored by git.

Conclusion:

It works whether you have a .gitignorefile or not, and whether or not you have added node_modules to git tracking. The most significant benefit is that you don’t have to manually update the .gitignore file each time. Comment down more such git one-liner that helped you.

Thats all for now. Feel free to hit me on Twitter! Also, do check out my repositories on GitHub and don’t hesitate to reach out to me if you would like to work on any of my existing projects or think I would be a good fit in your project :)