Felix Rieseberg

Dependencies and Git branches

Picture this: You're working on a decently sized project. It's 2019, so naturally, your node_modules folder contains thousands of files – and every single time you switch between branches, you need to run npm install again. Even if you're not working with Node.js, you might have dependencies that you need to re-install every single time you switch between feature branches. Or, maybe you have long-running compilation tasks that keep your working directory busy and you'd like to do work in some other branch while you wait.

What if you could tie your dependencies (like a node_modules folder) to your git checkout without actually checking the folder in? git worktree is a feature that supports this use case. In short, it helps you manage multiple working trees.

Run the following command to create a new working directory for a Git branch. This folder can be anywhere, but it should not be in your current repo.

git worktree add ../new-directory my-feature-branch

Git will then create a new directory at ../new-directory, checked out to your branch. Whenever you run git checkout my-feature-branch, it'll automatically switch to that folder. Switch to another branch, and you'll be back in your default folder.

This is useful for tons of reasons:

  • Run long-running processes (compilation, installation of dependencies, tests) in one branch, continue working in another branch
  • Have multiple branches of your project ready to work – worktrees allow me to be on a plane and work in multiple branches without hoping that npm's cache has everything I need.

Git introduced this feature back in 2015, but I believe that it doesn't quite have the popularity it deservers. Use it! It's amazing!