How to add ignored files from develpoment branch to a deploy branch in git

I have a particular issue that isn't quite covered by the scenarios I have found so far, here, here and here (amongst others).

I have a node.js project and have decided not to include the node_modules directory in my git repo (Here are some arguments for and against). However, I am setting up a regular deployment to a testing server and for this I would like to deploy the complete application, with the dependencies loaded (maybe in future I will also include the node server too, but for now just the dependencies).

So I create a test-deploy branch, on which I ignore the vagrant folder, some static pages, etc. I include the node_modules by removing it from the .gitignore file and then push the branch to a remote repository where I have set up hooks to inform my test-server there is a new deploy and it should pull from the remote.

How do I now go about checking out my development branch again? I have tried to add the node_modules back to the .gitignore file but when I checkout my development branch git (rightly so) removes all my node modules as they are not seen as part of the project.

While writing this question I was trying some ideas and came across this answer on how to ignore previously committed files. Following this, after replacing the node_module directory in the .gitignore file I then ran the command

git rm -r --cached node_modules/*

adding the -r flag to deal with recursive directory traversal. Now when I swap back to to the development branch my module files are still there (although I lost my Vagrant box!)

So to summarise, in order to include ignored files in a deploy branch and not lose them when you checkout your development branch again you should:

  • Checkout your deploy branch.
  • Remove node_modules/* from your .gitignore file
  • Add your module files to staging and commit, push or whatever you need to do
  • Add node_mudules/* to your .gitignore files again
  • Run git rm -r --cached node_modules/* to remove the files from the repository again.
  • Now you can checkout your development branch without losing your node modules from that branch.