Is there a way to confirm a package-lock.json actually resolves all dependencies in a package.json?

Viewed 25737

We want to add an automated check to our CI server that would prevent code from getting committed that updates a dependency in package.json but does not update the resolved dependency in package-lock.json.

This could happen if, for example, someone updated a dependency in package.json manually but ran npm install instead of npm update (npm install favors package-lock.json, if present). Or it could happen even if someone runs the correct npm command when updating a dependency but then forgets to commit the resulting changes to package-lock.json. We try to watch for these things in code review, but an automated check would definitely be better. Is there any npm command that does this?

Here's an example to illustrate.

Before:

// package.json
{
    "lodash": "~3.1.0"
}

// package-lock.json
{
    "dependencies": {
       "lodash": {
           "version": "3.1.3"
       }
    }
}

Someone updates package.json but forgets to commit the change to package-lock.json.

After:

// package.json
{
    "lodash": "~3.2.0"
}

// package-lock.json (not changed)
{
    "dependencies": {
       "lodash": {
           "version": "3.1.3"
       }
    }
}

Now package-lock.json no longer reflects a valid set of dependency resolutions for the package.json file.

3 Answers

...

Or to keep it simple you could just run npm ls at some point in your CI before npm install.

It doesn't cover case with initial npm install when there are not node_modules (what in case of CI server could be every time)

Use npm ci (https://docs.npmjs.com/cli/ci) available since 5.7.x version.

npm ERR! cipm can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file with `npm install` before continuing.
npm ERR! 
npm ERR! 
npm ERR! Invalid: lock file's core-js@2.5.7 does not satisfy core-js@^3.0.0-alpha.4

Use the npm ci command. It checks to make sure that the package.json and the package-lock.json are always in sync.

If they go out of sync, you get an error similar to

npm ERR! 

npm ERR! Invalid: lock file's yuglify@2.0.0 does not satisfy yuglify@^2.0.1
Related