简体   繁体   English

使 `npm install --save` 添加一个严格的版本到 package.json

[英]Make `npm install --save` add a strict version to package.json

When you run npm install --save somepackage , it usually adds something like this into package.json:当您运行npm install --save somepackage ,它通常会在 package.json 中添加如下内容:

"dependencies": {
    "somepackage": "^2.1.0"
}

Because the version is prepended with a caret(^), this means that if you later run npm install , it might install version 2.3.0 instead.因为该版本前面带有插入符号 (^),这意味着如果您稍后运行npm install ,它可能会安装版本 2.3.0。 This can be undesirable for fairly obvious reasons.由于相当明显的原因,这可能是不可取的。 npm shrinkwrap is useful, but doesn't really solve the problem. npm shrinkwrap很有用,但并不能真正解决问题。

So, I have several questions:所以,我有几个问题:

  1. When installing a package, is it possible to specify that you want it to be set to a specific version in package.json (no caret before the version number)?安装包时,是否可以指定要在 package.json 中将其设置为特定版本(版本号前没有插入符号)?
  2. When publishing a package to npm, is there any way to prevent the default of including the caret before the version when other developers install your package?在将包发布到 npm 时,有什么方法可以防止其他开发人员安装您的包时默认在版本之前包含插入符号?

To specify by default a exact version, you can change your npm config with save-exact :要默认指定确切版本,您可以使用save-exact更改 npm 配置:

npm config set save-exact true

You can also specify the prepend version with a tilde with save-prefix .您还可以使用带有save-prefix的波浪号指定前置版本。

And, no you can't force user to update to a minor or a patch version, NPM uses semver and it's the recommend way of publishing packages.而且,您不能强制用户更新到次要版本或补丁版本,NPM 使用semver ,这是发布包的推荐方式。

You can change the default behaviour by using the --save-exact option.您可以使用--save-exact选项更改默认行为。

// npm
npm install --save --save-exact react

// yarn
yarn add --exact react

I created a blog post about this if anyone is looking for this in the future.如果将来有人在寻找这个,我创建了一篇关于此的博客文章。

https://www.dalejefferson.com/blog/how-to-save-exact-npm-package-versions/ https://www.dalejefferson.com/blog/how-to-save-exact-npm-package-versions/

Run:跑:

npm install --save --save-exact my-module@my-specific-version

Adding an answer to make this advice easier to see.添加答案以使此建议更易于查看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM