February 2023
2 minute read
Navigating lock files: best practices and tips
Martin Torp
By Martin Torp
Cofounder of Coana
PhD in Computer Science

<m>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:</m>

<m>* **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](https://gist.github.com/szemate/6fb69c8e3d8cce3efa9a6c922b337d98) for more details.</m>

<m>* **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](https://stackoverflow.com/a/69944063) for more details)</m>

<m>* **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](https://github.com/imsnif/synp) to convert yarn.lock files to package-lock.json.</m>

<m>* **Don’t change lock files manually:** Use `npm update` and `npm install` to add and update packages.</m>

<m>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.</m>

Questions or opinions?

Feel free to reach out to us by email or through our Slack Community anytime. We'd love to hear from you.

Join waitlist

Sign up to get notified about future Coana future launches.