2

Is there a way to check if a package-lock.json file is compatible with package.json without running npm install? Compatible means the versions specified package.json can be fulfilled by package-lock.json.

Current approach

I'm currently checking this by running npm install and checking if package-lock.json changed like so:

git clone https://github.com/my/codebase
cd codebase
npm install
if [[ git diff-index --quiet HEAD -- package-lock.json ]]; then
  echo 'ERROR: npm install changed package-lock.json'
fi

Use-case

I want to add a test in continuous integration to ensure that if a developer modifies package.json they also update package-lock.json accordingly. The reason this is important is that our continuous integration uses npm ci instead of npm install. npm ci only references package-lock.json, so if the developer doesn't update the lock file, the continuous integration setup won't match what they expect.

Joe
  • 3,370
  • 4
  • 33
  • 56
  • `npm ci` will fail if the package.json and the package-lock.json are not in sync, so your continuous integration is already testing your use case. Can you please provide more information about the difference you are finding between your developer's setup and the CI one? – Gnafu Oct 04 '19 at 08:20
  • Yep, I verified this works for version numbers. However, I found this not to be true when using a Git revision. Repro and details at https://npm.community/t/npm-ci-doesnt-validate-versions-for-git-hashes-between-package-json-and-package-lock-json/10213 – Joe Oct 04 '19 at 20:26

2 Answers2

2

As someone in the comments mentioned, there's the npm ci command, which will throw an error if package.json is not in sync with package-lock.json.

Here's what I use to "test" that they are on parity:

ERRORS=0
npm ci
if [[ "$?" -ne 0 ]]; then
    echo "Dependency installation failed!"
    ERRORS=$(($ERRORS+1))
fi

I'm looking for a better way to do this since this actually removes the entire node_modules directory, confirms parity, and then proceeds to install the locked versions if all is well, but that takes some time depending on the number of packages.

Scorpius
  • 999
  • 1
  • 10
  • 22
0

It took me few months to discover that npm ci is not your friend as it would miss to sync updated engines from package.jsonintopackage-lock.json. Thus I think that the answer is npm install --production`

All the kudos should go to https://stackoverflow.com/a/19824154/99834 which explains it in detail. For convenience I will mention the most important bits:

  • npm install will install/update devDependencies unless --production flag is added
  • npm update will ignore devDependencies unless --dev flag is added
sorin
  • 161,544
  • 178
  • 535
  • 806