I have a repo with two branches, and I don't know how to handle the git ignored node_modules folder that should contain different packages in the two branches.
From my understanding, git-worktree
is the correct approach, but I can't figure out how to use it.
Because the two branches already have many commits, I need a solution that preserve all of them.
At the moment, every time a checkout, I run:
rm -r node_modules
npm install
But because this process is not convenient, I investigated, and it looks that the suggested solution is to use git worktree
.
Somewhere else, it doesn't seam the correct approach.
If it is the correct approach, I can't figure out how to use it in practice.
If I run:
git worktree add ./node_modules <current_branch_name>
I get:
fatal: '<current_branch_name>' is already checked out at '/some/path/my-project-folder'
If I run
git worktree add ./node_modules <other_branch_name>
The folder is created, but running npm install
the packages are installed in it, making it unusable when I switch branch with git checkout <other_branch_name>
.
If I create two folders with:
git worktree add ./node_modules_foo <current_branch_name>
git worktree add ./node_modules_bar <other_branch_name>
They are created, but not used by npm install
unless I move the package.json
files in them, that is not what I want and could be done also without git worktree
.
Is it git worktree
the correct approach for this problem and how to use it correctly?
I also investigate another approach, to specify a different installation folder in the package.json
file, but it looks it is not an option.
Going by what the linked article said:
Use directory ../branch1
to work on branch branch1
:
git worktree add ../branch1 branch1
So a sibling directory.
Then likewise for branch2
:
git worktree add ../branch2 branch2
But the article is wrong about this though:
Whenever you run
git checkout my-feature-branch
, it'll automatically switch to that folder.
No. The worktrees are checked out at those branches, and you cannot change those branches in the current worktree; you will have to do cd ../branch1
to “check out” branch1
and likewise for branch2
. (If you try git checkout branch1
you will get a fatal
error, since you have checked out branch1
in another worktree; you will not automatically change the directory to ../branch1
.)
I guess the idea here is to “freeze” a branch on each worktree so that you don’t have to blow away that node_modules
bloat on every branch change.
Just do:
cd ../branch1
npm install
And:
cd ../branch2
npm install
And then change directory back to whichever when you need to work on them again; node_modules
(if it is untracked, anyway) won’t have been disturbed so there won’t be a need to rm -r node_modules
.
At least that’s what I think the article is about.