Search code examples
javascriptyarnpkg

How does yarn work when it encounters ^ (caret) with a lock file?


How does yarn work when it encounter a ^ (caret) in package.json dependencies?

Let's say I have react: ^16.0.0 and when I yarn install, it will create a lock on that version (16.0.0).

Now sometime later when react 16.1.0 is released, and I yarn install again with the lock file, will yarn upgrade it to that version or follow what is in the lock file which is 16.0.0?

Thanks.


Solution

  • yarn install will install the exact version in the lockfile. That's the great benefit of a lockfile, everyone working on your project gets the exact same version of the package regardless of when the do yarn install. (e.g. I do yarn install today, when 16.0.0 is the current version, but you do yarn install tomorrow when 16.1.0 is the current version. We'll still both get 16.0.0 because that's what our lockfile says we should get. Our development environments are exactly the same, which is what we want. Likewise if we deploy in 2 weeks when 16.2.0 is the current version, 16.0.0 will get deployed; thus our dev and prod environments are exactly the same, too)

    If 16.1.0 is released and you want to update your project to use it, use yarn upgrade. Note that you can upgrade all of your packages, or just one specific package, as well as update to the latest version of a package or a specific version of a package. https://yarnpkg.com/lang/en/docs/cli/upgrade/

    Version Control Your package.json and yarn.lock

    By adding these two files to version control, you'll easily be able to revert your project to a specific point in time in regards to your packages.

    Edit in 2024 -- Read the Question, and Read the Other Answer**

    OPs question was how yarn behaves with a caret and a lock file:

    will yarn upgrade it to that version or follow what is in the lock file which is 16.0.0?

    Here's the important concept: yarn behaves very differently if you are using a lock file, than if you are not using a lock file.

    If you're wondering what a caret means without a lock file, read the other answer by thecaveman (excepting his comment that this answer here is wrong...it is not). But know that if you are using a lock file, like OP asked, you need to read this answer above to understand how yarn behaves.