【问题标题】:How to pass parameters to a script processed by ts-node如何将参数传递给 ts-node 处理的脚本
【发布时间】:2019-05-31 03:48:43
【问题描述】:

我刚开始使用 ts-node。这是一个非常方便的工具。运行时间看起来很清晰。但它不适用于 CLI 解决方案。我无法将参数传递到已编译的脚本中。

ts-node --preserve-symlinks src/cli.ts -- printer:A

它不起作用。我正在寻求帮助。

【问题讨论】:

    标签: ts-node


    【解决方案1】:

    您没有提供脚本,所以我只能猜测您是如何提取参数的。这就是我如何使用我自己的测试脚本args.ts

    const a = process.argv[2];
    const b = process.argv[3];
    const c = process.argv[4];
    console.log(`a: '${a}', b: '${b}', c: '${c}'`);
    

    像这样从package.json 调用:

    "scripts": {
       "args": "ts-node ./args.ts -- 4 2 printer:A"
    }
    

    这会给我这样的输出:

    a: '4', b: '2', c: 'printer:A'
    

    【讨论】:

      【解决方案2】:

      试试这个:

      node --preserve-symlinks -r ts-node/register src/cli.ts printer:A
      

      【讨论】:

        【解决方案3】:

        NODE_OPTIONS

        对于节点选项的情况,除了https://stackoverflow.com/a/60162828/895245 中提到的-r ts-node/register,他们现在还在文档中提到了NODE_OPTIONS 环境变量:https://typestrong.org/ts-node/docs/configuration/#node-flags

        NODE_OPTIONS='--trace-deprecation --abort-on-uncaught-exception' ts-node ./index.ts
        

        快速测试:

        main.ts

        (async () => { throw 'asdf' })()
        

        然后运行:

        NODE_OPTIONS='--unhandled-rejections=strict' ts-node main.ts
        echo $?
        

        如预期的那样给出1

        在节点 v14.16.0、ts-node v10.0.0 上测试。

        【讨论】:

          【解决方案4】:

          命令

          ts-node ./test.ts hello stackoverflow
          

          ts 文件

          console.log("testing: >>", process.argv[2], process.argv[3]);
          

          输出

          $ testing: >> hello stackoverflow
          

          愉快的编码

          【讨论】:

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