node.js 从命令行编辑 package.json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25329241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:45:56  来源:igfitidea点击:

Edit package.json from command line

jsonnode.jsnpm

提问by DerZyklop

I'm trying to add or edit a variable in my package.json from a shell script. So if i have a package.json like this:

我正在尝试从 shell 脚本添加或编辑 package.json 中的变量。所以如果我有一个这样的 package.json:

{
  "name": "my-project",
  "description": "Project by @DerZyklop",
  "version": "0.0.0",
  ...

I want a?command like

我想要一个?命令像

npm config set foo bar

that adds a new field like

添加了一个新字段,例如

{
  "name": "my-project",
  "description": "Project by @DerZyklop",
  "foo": "bar",
  "version": "0.0.0",
  ...

...but unfortunately npm config setjust edits the ~/.npmrcand not my package.json.

...但不幸的是npm config set只编辑~/.npmrc而不是我的 package.json。

回答by enrico.bacis

The package.jsonis just a jsonfile, so you could use the tool json. To install it use:

package.json只是一个json文件,因此您可以使用该工具json。要安装它,请使用:

npm install -g json

Then you can edit a file in-place. More information here.

然后您可以就地编辑文件。更多信息在这里

Example

例子

$ cat package.json
{
  "name": "my-project",
  "description": "Project by @DerZyklop",
  "version": "0.0.0"
}

$ json -I -f package.json -e 'this.foo="bar"'
json: updated "package.json" in-place

$ cat package.json
{
  "name": "my-project",
  "description": "Project by @DerZyklop",
  "version": "0.0.0",
  "foo": "bar"
}

回答by Bertrand Martel

You can also use jqand sponge(moreutils package) like this :

您还可以像这样使用jq海绵(moreutils 包):

jq '.foo="bar"' package.json | sponge package.json

With an environment variable :

使用环境变量:

jq --arg h "$HOMEPAGE" '.homepage=$h' package.json | sponge package.json

回答by Amy Guo

If you don't want to install spongeor json, you can also do

如果你不想安装海绵json,你也可以这样做

echo "`jq '.foo="bar"' package.json`" > package.json

回答by Zeke

There's also a npm package for doing this called npe: https://github.com/zeke/npe

还有一个 npm 包用于执行此操作,称为npehttps: //github.com/zeke/npe

cd some/node/project

# Get stuff from package.json
npe name
npe scripts
npe scripts.test
npe repository.url
open $(npe repository.url)

# Set stuff in package.json
npe name foo
npe scripts.start "node index.js"

# Keywords string will be turned into an array
# If commas are present, they'll be the delimiter. Otherwise spaces.
npe keywords "foo, bar, cheese whiz"
npe keywords "foo bar baz"

# The current working directory's package.json is used by default,
# but you can point to another package file with a flag:
npe name --package=some/other/package.json
npe name other --package=some/other/package.json