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.
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.
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 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!
Finally, ignore any packages that are actually worktrees. The pattern here is to start worktree directory names with with wt-.
packages/wt-*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With