Video Lesson: Pin npm package versions with yarn.lock in Docker

Pin npm package versions with yarn.lock in Docker

Learn how to use lockfiles to ensure consistent dependency versions and reproducible installations across environments.


Lesson Content

NPM does not guarantee fully deterministic installs. Even with npm shrinkwrap, running npm install on two different computers can produce different results.

Yarn solves this by recording the exact package versions it installs in a yarn.lock file. Yarn is designed to provide deterministic, reliable, and fast installs.

To install a package, use yarn add followed by the package name. For example, create a new project and add React:

mkdir foo && cd $_
git init
yarn add react

You can also install a specific version:

yarn add [email protected]

Or specify a version range if you want Yarn to choose a compatible version:

yarn add react@^15.0

After the first package is installed, Yarn creates a yarn.lock file. Open that file and search for the package name (/react in Vim) to see the exact version that was selected:

vi yarn.lock

The lock file also contains integrity information. Yarn uses these checks to verify that it downloads the exact package contents recorded for the dependency, which helps produce the same installation across environments.

Add both package.json and yarn.lock to version control. The package.json file describes the project dependencies, while yarn.lock pins the complete dependency tree to specific versions and download checksums.

Do not commit node_modules. These files are generated when Yarn runs during the build or after deployment. Add the directory to .gitignore instead, then commit:

git add package.json yarn.lock
echo "/node_modules" >> .gitignore
git add .gitignore
git commit -m "Initial commit"

With package.json and yarn.lock committed, and node_modules ignored, each environment can install the same dependency versions without storing generated packages in the repository.

Maggie

Hey, I'm Maggie! 👋

Ask me anything.

Want to chat with Maggie?

Log in for AI tutor access.

Comments

Join the discussion!

Notes

Keep track of what you learn!