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 .gitignore
file.
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.
Explanation
- Creating gitignore, if not available already
If the .gitignore
file doesn’t already exist, touch
will create it.
2. Adding new node_modules path to gitignore
echo >>
will add node_modules/
inside the .gitignore
at the end, causing thenode_modules
folder and all subfolders to be ignored.
3. Remove the pre-existing files, if any
If the node_modules
folder was previously added to git control, git rm -r --cached
removes it. If not, a warning that the pathspec 'node_modules' did not match any files
will 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 .gitignore
file 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 :)