Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include node_modules when using git worktree

I have a big node repo that has a node_modules folder, which is untracked (included in the .gitignore file).

I recently started learning about git worktrees and I would like to be able to add worktrees that include the node_modules folder without having to run npm install on that worktree. Is there a way to accomplish that without editing .gitignore or copying the folder manually? I just would like to have worktrees ready to go when creating them.

like image 406
sebastian gallardo Avatar asked May 02 '26 06:05

sebastian gallardo


1 Answers

npm workspaces

npm workspaces automatically symlink the node_modules directory for all child projects (workspaces) that have a packages.json.

Here is an example project structure

PROJECT /
   node_modules 
   packages / 
     client / 
         package.json
     server / 
          package.json
     wt-main/
           client/
           server/
   package.json

All of the workspace packages have their own package.json but will share the top-level node_modules.

Run npm install from the root to resolve dependencies for all workspaces. npm install dependencies for specific workspaces with npm install package -w workspace. For example, I can stall foo for my wt-main workspace by doing npm install foo -w packages/wt-main.

Workspace configuration in package.json

  "workspaces": [
    "packages/*"
  ]

The above configuration assumes all the worktrees are in packages/. The worktree name cannot be the same as the branch. Hence why the main branch worktree is name wt-main instead of just main.

Create a worktree

Create new worktree for main branch

git worktree add packages/wt-main

Switch to the worktree

cd packages/wt-main

Start the NPM project like normal

npm run start (or whatever is used)

There will be a noticeable lack of node_modules anymore in the workspaces / worktrees but the project still works!

.gitignore

Finally, ignore any packages that are actually worktrees. The pattern here is to start worktree directory names with with wt-.

packages/wt-*
like image 158
NatesCode Avatar answered May 04 '26 21:05

NatesCode