2

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.

yevg
  • 1,846
  • 9
  • 34
  • 70
  • 1
    `package.json` is required - if you ever wish to add a package, it will require the use of `package.json` - not to mention it contains the central place for human-readable analysis of packages used AND project attributes (commands, project locations, etc etc) – Derek Pollard Apr 15 '19 at 18:31
  • Not to mention, you cannot have a project with only `package.json` - npm wouldn't know what to do upon install for new developers – Derek Pollard Apr 15 '19 at 18:33

2 Answers2

3

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.

Gonzalo Matheu
  • 8,984
  • 5
  • 35
  • 58
2

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.

Martin Poelstra
  • 300
  • 1
  • 6