What's the difference between tilde(~) and caret(^) in package.json?

后端 未结 19 1847
温柔的废话
温柔的废话 2020-11-22 00:31

After I upgraded to latest stable node and npm, I tried npm install moment --save. It saves the entry in the package.json

相关标签:
19条回答
  • 2020-11-22 01:05

    Semver

    <major>.<minor>.<patch>-beta.<beta> == 1.2.3-beta.2
    
    • Use npm semver calculator for testing. Although the explanations for ^ (include everything greater than a particular version in the same major range) and ~ (include everything greater than a particular version in the same minor range) aren't a 100% correct, the calculator seems to work fine.
    • Alternatively, use SemVer Check instead, which doesn't require you to pick a package and also offers explanations.

    Allow or disallow changes

    • Pin version: 1.2.3.
    • Use ^ (like head). Allows updates at the second non-zero level from the left: ^0.2.3 means 0.2.3 <= v < 0.3.
    • Use ~ (like tail). Generally freeze right-most level or set zero if omitted:
    • ~1 means 1.0.0 <= v < 2.0.0
    • ~1.2 means 1.2.0 <= v < 1.3.0.
    • ~1.2.4 means 1.2.4 <= v < 1.3.0.
    • Ommit right-most level: 0.2 means 0.2 <= v < 1. Differs from ~ because:
      • Starting omitted level version is always 0
      • You can set starting major version without specifying sublevels.

    All (hopefully) possibilities

    Set starting major-level and allow updates upward

    *  or "(empty string)   any version
    1                         v >= 1
    

    Freeze major-level

    ~0 (0)            0.0 <= v < 1
    0.2               0.2 <= v < 1          // Can't do that with ^ or ~ 
    ~1 (1, ^1)        1 <= v < 2
    ^1.2              1.2 <= v < 2
    ^1.2.3            1.2.3 <= v < 2
    ^1.2.3-beta.4     1.2.3-beta.4 <= v < 2
    

    Freeze minor-level

    ^0.0 (0.0)        0 <= v < 0.1
    ~0.2              0.2 <= v < 0.3
    ~1.2              1.2 <= v < 1.3
    ~0.2.3 (^0.2.3)   0.2.3 <= v < 0.3
    ~1.2.3            1.2.3 <= v < 1.3
    

    Freeze patch-level

    ~1.2.3-beta.4     1.2.3-beta.4 <= v < 1.2.4 (only beta or pr allowed)
    ^0.0.3-beta       0.0.3-beta.0 <= v < 0.0.4 or 0.0.3-pr.0 <= v < 0.0.4 (only beta or pr allowed)
    ^0.0.3-beta.4     0.0.3-beta.4 <= v < 0.0.4 or 0.0.3-pr.4 <= v < 0.0.4 (only beta or pr allowed)
    

    Disallow updates

    1.2.3             1.2.3
    ^0.0.3 (0.0.3)    0.0.3
    

    Notice: Missing major, minor, patch or specifying beta without number, is the same as any for the missing level.

    Notice: When you install a package which has 0 as major level, the update will only install new beta/pr level version! That's because npm sets ^ as default in package.json and when installed version is like 0.1.3, it freezes all major/minor/patch levels.

    • https://docs.npmjs.com/misc/semver
    • https://docs.npmjs.com/files/package.json#dependencies
    0 讨论(0)
提交回复
热议问题