【问题标题】:yarn/npm: Execute depending on set variableyarn/npm:根据设置变量执行
【发布时间】:2019-03-15 04:04:50
【问题描述】:

我基本上是 took this bash recipe 来运行不同的命令,这取决于 package.json 脚本是否带参数调用...

"scripts": {
    "paramtest": "if [ -z $1 ]; then echo \"var is unset\"; else echo \"var is set to {$1}\"; fi",
    ...

不带参数的调用按预期工作:

$>yarn paramtest
var is unset
$>npm run paramtest
var is unset
$>

用参数调用给我一个错误:

$>yarn run paramtest foo
/bin/sh: 1: Syntax error: word unexpected
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
$>npm run paramtest -- foo

> photocmd@0.0.7 paramtest /depot/own/photocmd

sh: 1: Syntax error: word unexpected
...

怎么了?

【问题讨论】:

    标签: bash npm yarnpkg


    【解决方案1】:

    根据this 的回答和this 的评论,yarn run 只支持将参数传递到脚本的末尾,而不支持传递到中间。此行为类似于npm run

    要规避此限制,您需要将当前的条件逻辑放在 bash function 的正文中。例如:

    "scripts": {
      "paramtest": "func () { if [ -z \"$1\" ]; then echo \"var is unset\"; else echo \"var is set to ${1}\"; fi ;}; func",
    ...
    

    现在,当您通过 CLI 将参数传递给脚本时,它会得到:

    1. 添加到 paramtest 脚本的末尾,即在 func 调用之后。
    2. 随后作为参数传递给func 函数本身。
    3. func 函数的主体中,第一个参数在测试中使用$1 引用,在echo 字符串中使用${1}

    注意:测试中的$1被json转义双引号包裹,即\"$1\"

    运行脚本:

    通过 CLI 将参数传递给脚本时,在脚本名称(即paramtest)和参数(foo)之间添加-- 会更安全。例如:

    yarn run paramtest -- foo
                       ^^
    

    因为如果您的参数以连字符开头(如以下命令所示),它将被解释为一个选项:

    yarn run paramtest -foo
                       ^
    

    你的脚本会打印出来:

    var is unset

    但是,添加--,如下例所示;

    yarn run paramtest -- -foo
                       ^^ ^
    

    正确打印:

    var is set to -foo

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多