DEV Community

Cover image for Navigating lock files: best practices and tips
Martin Torp
Martin Torp

Posted on

Navigating lock files: best practices and tips

If you are unsure about how to manage the package-lock.json (or yarn.lock) file in your project, you're not alone. This file is essential for ensuring that your project's dependencies are restored to the same versions on any machine where you run npm install(or yarn). This is important because without a lock file, legacy projects may break if a dependency version is changed between installations. Here are some best practices and tips for working with lock files:

  • Merge conflicts: Do not manually resolve merge conflicts in lock files. npm and yarn can do it for you automatically! If there are merge conflicts in the package.json file, first resolve them manually and then run the npm install (or yarn) command to automatically fix any corresponding conflicts in the lock file. See this gist for more details.

  • Use in CI: In CI environments, it is best to use npm ci (clean install) instead of npm install. npm ci will ensure a clean installation of dependencies by deleting the previous node_modules and by never making changes to package.json. npm install, on the other hand, may update the package-lock.json file if it is inconsistent with package.json. The yarn equivalent of npm ci is yarn install --immutable --immutable-cache --check-cache (See https://stackoverflow.com/a/69944063 for more details)

  • Converting between yarn.lock and package-lock.json: yarn uses yarn.lock and npm uses package-lock.json. You can convert a yarn.lock file to a package-lock.json using the yarn import command. Use synp to convert yarn.lock files to package-lock.json.

  • Don’t change lock files manually: Use npm update and npm install to add and update packages.

Lock files can be intimidating, but they are easy to work with as long as you avoid manually editing them. Following these practices will help ensure that your project runs smoothly.

Top comments (0)