What is the difference between "~" and "^" in npm?

NPM is used to install packages. These packages have versions, and in most cases, you will have to install specific versions that can accept future updates of features, bugs, etc.

The package.json file

NPM will install packages when you specify them in the dependencies field inside the package.json file.

Take a look at the example below.

{
  ...
  "dependencies": {
    "cors": "^2.8.5",
    "debug": "~2.6.9",
    "dotenv": "^8.2.0",
  }
  ...
}

Include a tilde (~) in an NPM package

The tilde (~) tells NPM to install the latest bug fixes known as PATCH(es). These bug fixes might include important security patches or any other important fixes.

From the package.json file above:

"debug": "~2.6.9"

This indicates that NPM will install version 2.6.x of debug package.

Include a caret(^) in an NPM package

The caret (^) tells NPM to install the latest features known as MINOR updates and PATCH(es). These features are backward compatible.

From the example above:

"dotenv" : "^8.2.0"

This indicates NPM will install version 8.x.x of dotenv.

Free Resources