【问题标题】:How to pass arguments and use those arguments as variables in a package.json script? [duplicate]如何传递参数并将这些参数用作 package.json 脚本中的变量? [复制]
【发布时间】:2020-03-03 13:01:13
【问题描述】:
"scripts": {
    "cr": "git commit -am ${message} && git pull origin master --rebase && git push --force",
}

我正在尝试弄清楚如何使用以下内容运行上述内容:

# yarn cr "commit message"

【问题讨论】:

  • 似乎作为 shell 别名会更好?确保使用--force-with-lease 来避免比赛。
  • 您可以尝试修改整个 package.json 文件以替换它的任何部分。你需要先解析JSON,然后改变对应的key值,然后将生成的JSON字符串化并保存到文件中。
  • 我觉得必须有一个简单的解决方案?并且 shell 别名可以工作,但我希望任何拉下项目的人都可以轻松地重复使用它。

标签: git npm package.json npm-scripts


【解决方案1】:

sh -c 'shell_command' 模式适用于 *nixWindows Powershell。然后,您可以使用$0$1 等来访问命令行参数。所以把这个写在你的package.json

"scripts": {
    "cr": "sh -c 'git commit -am $0 && git pull origin master --rebase && git push --force'",
}

现在您可以在终端中运行此命令:

yarn cr commit_message

【讨论】:

  • 当 npm 使用的默认 shell 是 cmd.exe 时,这将在 Windows 上失败
  • 感谢您的意见。我在 Ubuntu 和 Windows Powershell 上对其进行了测试,效果很好。
  • 确定 Ubuntu 是 *nix 在这种情况下 npm 默认使用 sh。 Powershell 通常默认使用cmdnpm docs 状态:“默认情况下,在类 Unix 系统上是 /bin/sh 命令,在 Windows 上是 cmd.exe。”。要获得真正的跨平台兼容性,您需要从 node.js 脚本中脱壳 - 例如,请参阅我的答案 here
【解决方案2】:

是的。 你可以做这样的事情

"scripts": {
{
  "cr": "f(){ git commit -am $1;};f",

}
}

yarn run cr -- 'commit message'

您可以传递 n 个以空格分隔的参数,并且可以通过 $1 ,$2 .. 访问。

【讨论】:

  • 当 npm 使用的默认 shell 为 cmd.exe 时,这将在 Windows 上失败
  • 这将适用于 unix。请在 windows 中使用 gitbash
猜你喜欢
  • 2015-09-20
  • 2016-05-15
  • 2020-02-14
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
  • 2018-07-29
相关资源
最近更新 更多