How to Remove Already Tracked File in Git


While working with Git you can easy get in situation that you committed some files that should be ignored (for example node_modules folder or dist folder). Here are easy steps for to fix such problem. Let's jump right into it.

Content

First of all let's reproduce the problem. Here I have an empty folder with initialized git. Let's simply write

npm install express

As you can see node_modules folder was created for us and it's not tracked by Git yet. So really often, especially after generating new project you can forget than node_modules was generated and was not ignored. Normally of course we want to create .gitignore file and add it there. But let's say that we forget to do that.

git add .

So git add with dot will add all untracked files to git. And probably we wanted to commit our code and wrote git add and now we are checking status and there are hundreds of files.

Even if we create .gitignore with node_modules line inside it won't change anything because node_modules is already tracked by Git. Let's do this now.

As you can see it doesn't help.

What we need to do it to remove node_modules folder from git cache.

git rm -r  --cached  node_modules

So we need here cached parameter to just remove folder from git index. As you can see after this command we don't see node_modules in git status anymore and they are properly ignored.

And just to remind you, you should never ever commit node_modules or build files to repository because it doesn't make any sense. All your versions dependencies should be resolved with lock files. I made a video about it. If you didn't watch it I will link it don't in the description. And all build or minified files you can always generate again. If you commit them it's difficult to check your changes in Pull Requests for example and you repository becomes full or generated and not needed code.

Call to action

So if you forget to add something to gitignore and commited or even pushed it it's not a problem. Just add it to gitignore, remote from git index and commit your changes.

Also I have a lot of full courses regarding different web technologies. So don't forget to check them out. I will link them down in the description box below.

If you find this video helpful, don't forget to subscribe to this channel and hit subscribe button. Thanks for watching and I see you in my next video.

🚨 Important