yevg
yevg

Reputation: 1966

Managing package.json & package-lock.json with Git

I know you're supposed to add package-lock.json to your git repo to ensure team members are using the same versions of dependencies.

Running npm install will check for a package-lock.json and install the versions indicated there. If a lock file is not present it will install packages from their sources as indicated by package.json.

Should package.json be added to your git repo as well, then?

If not, a new team member who clones the repo would get the lock file but a package.json file cannot be generated from a lock file, correct?

Bonus question: How should one handle merge conflicts in package-lock.json? Since they are machine-generated, I find that this happens often and its not always clear how they should be resolved.

Upvotes: 3

Views: 4577

Answers (2)

Gonzalo Matheu
Gonzalo Matheu

Reputation: 10064

Yes, package.json should be included as well. Besides containing project metadata and being required by npm, it provides a clean and concise view of explicit dependencies.

Regarding conflicts, the best option might be to use one of them entirely (not trying to merge). Or just re-create it from scratch. You might be having many conflict in the early phases of a project where all main dependencies are being added.

Upvotes: 3

Martin Poelstra
Martin Poelstra

Reputation: 330

To answer your bonus question:

There's a way to teach Git to automatically 'merge' package-lock.json files, using a merge driver and a .gitattributes file.

TL;DR

Run this once on each developer machine:

git config --global merge.theirs.name "Keep changes of upstream branch"
git config --global merge.theirs.driver "cp -f '%B' '%A'"

Add the following .gitattributes file to your repo (and commit it):

package-lock.json merge=theirs

See my blog post for a more detailed explanation.

Upvotes: 4

Related Questions