Home > Back-end >  Configuring package-lock.json to be source of dependency truth
Configuring package-lock.json to be source of dependency truth

Time:04-21

I had the exact same question as Do I need both package-lock.json and package.json? (tldr; "what's the difference between package.json and package-lock.json?") and found some really great answers in there. However it leaves me with a few other very similar-related questions that I don't see answered elsewhere.

For instance, what if package.json and package-lock.json conflict with one another? Say package.json says to use some-lib-2.* (any 2.x version of some-lib) but package-lock.json is configured to use some-lib-1.18.4? Is there an error? Is preference given to either file as the "source of dependency truth"?

I like the idea of one file to manage my specific dependencies, and so I feel like I'm leaning towards:

  1. Not specifying libraries or version in package.json at all; and
  2. Using package-lock.json to specify the exact versions of each module/library my project uses

Is this possible to do? If so are there any special configurations that I need to make? Do I track both files in version control, or is there ever any reasons why I would not want to track these in git/VCS?

CodePudding user response:

Really shocked a whole day went by with no answers to this. Java questions usually get eaten up in minutes! Especially basic ones, yikes!

  1. You use the the command line (npm install [optional args]) to update both files.
  2. NPM -- and your command line invocation -- decide what the acceptable ranges of dependency versions there are for module and define those ranges in package.json. It then picks a version within that range -- uses it for buildtime/runtime -- and writes that exact version in package-lock.json
  3. So you want to place both files in version control so you have repeatable builds and any developers checking out your project will immediately be able to build the project with the same versions of the same dependencies
  4. And the only time you edit package.json directly is if you don't want to allow a range of versions for a particular dependency and want to cherry pick the exact version to use. You make the edit, you save, you run npm install [options] and package-lock.json will be updated to use that version as well

FWIW this is terribly confusing and advocates the anti-pattern of not managing your dependencies. It allows developers to think its OK to just pull in the latest version of a given dependency, even if that version changes from build to build. That leads to bug creep in your application, non-repeatable builds and all sorts of headaches.

I would strongly advocate for always specifying the exact version you want for all your direct dependencies: no more ranges or wildcards please.

  • Related