How to set exact dependency versions in package.json without using npm-shrinkwrap?

I’m trying to find a way to specify the exact versions of installed dependencies in my package.json file. I don’t want to use the latest available versions or rely on npm-shrinkwrap.json.

Is there a method to achieve this without extra tools or config files? I’ve looked into npm shrinkwrap but it creates a separate file instead of updating package.json directly.

Here’s what I’ve tried so far:

// Attempted to modify package.json manually
{
  "dependencies": {
    "express": "4.17.1",
    "lodash": "4.17.21"
  }
}

But this approach is tedious and error-prone. Is there an automated way to update package.json with the exact installed versions? Any help would be appreciated!

hey man, try this out:

npm install --save-exact

it’ll lock down the exact versions in ur package.json when u install stuff. no need for extra files or complicated commands. just run that before installin dependencies and ur good to go

I’ve been in your shoes, and I found a nifty solution that might help. Instead of manually editing package.json or relying on npm-shrinkwrap, you can use the npm ls command combined with some shell magic to update your package.json automatically.

Here’s what I do:

  1. Run npm install to ensure all packages are installed
  2. Use this command: npm ls --json --depth=0 | jq '.dependencies | to_entries | map_values({(.key): .value.version}) | add' > temp.json
  3. Then: jq '.dependencies = input' package.json temp.json > package.json.new && mv package.json.new package.json

This approach uses jq to parse the JSON output from npm ls and update your package.json with exact versions. It’s automated and keeps everything in your package.json without extra files.

Just make sure you have jq installed on your system. It’s saved me tons of time and headaches when managing dependencies across projects.

I’ve found a reliable method for maintaining exact dependency versions without resorting to npm-shrinkwrap. The npm ci command is particularly useful as it installs dependencies strictly based on your package-lock.json, ensuring version consistency across environments.

To implement this approach, first run ‘npm install’ to generate an up-to-date package-lock.json. Then, commit both your package.json and package-lock.json to version control. Finally, use ‘npm ci’ for all subsequent installations. This strategy keeps everything within your project’s standard files and has significantly improved deployment consistency, reducing many of the common environment issues.