【问题标题】:Use a separate file for "scripts"为“脚本”使用单独的文件
【发布时间】:2019-05-29 09:21:31
【问题描述】:

在我的 package.json 文件中,“脚本”中有很多命令,如下面的代码。

"scripts" {
  "script1": "command example",
  "script2": "command example",
  "script3": "command example",
  "script4": "command example",
  "script5": "command example",
  "script6": "command example",
  "script7": "command example",
  ...
}

有没有办法将这些命令移动到另一个文件?

例如,我正在考虑将它们移动到像 bin/commands.js 这样的文件中。

【问题讨论】:

  • “太多”是什么意思?是抛出错误还是什么?
  • @Phil 我应该说,“有这么多命令”。没有由此引起的任何错误。我只是想将所有命令分开以获得更好的可读性。
  • 您可以使用 Makefile 作为 package.json 脚本的替代方案
  • 您可以根据运行不同的脚本创建一个接受参数的脚本。
  • 对于我的一生,IDK 为什么他们选择在 package.json 文件中“仅”提供它。他们制作了.npmrc 属性文件,因此不能在该文件中使用 JSON。我将在 2022 年写这篇文章,但我仍然没有看到任何好的解决方案。我正在考虑尝试设计一种新的解决方案,但我猜测是否已经在 NPM 模块中实现了它......

标签: javascript npm package.json


【解决方案1】:

这是一个常见问题,您的 package.json 会因过多的脚本而变得臃肿。 Kent Dodds 构建了一个非常好的解决方案,称为 NPS (npm-package-scripts)。不幸的是,这个问题没有很多解决方案。

专业版:您在 js 文件中定义脚本,这样您就拥有更大的灵活性,减少 package.json 中的混乱,良好的社区支持。

CON:不是很多,只是一个不同的命令(nps vs npm)

【讨论】:

    【解决方案2】:

    您可以创建一个单独的脚本如下

    shell脚本

    if [ $1 == "1" ]; then
            sh <path to script1>
    elif [ $1 == "2"]; then
            sh <path to script2>
    else
            echo "script does not exist"
    fi
    

    节点脚本

    {
        var exec = require('child-process-promise').exec;
        let args = process.argv[2];
        let obj = {
            "script1": "command example",
            "script2": "command example",
            "script3": "command example",
            "script4": "command example",
            "script5": "command example",
            "script6": "command example",
            "script7": "command example"
        }
        exec(obj[`script${args}`]).then(result => {
            console.log(result.stdout);
        })
    }
    

    然后在 package.json 你可以有

    "scripts": {
       "myscript": "script.sh"[or "script.js"]
    }
    

    然后使用你的脚本作为

    npm run myscript 1
    

    【讨论】:

      猜你喜欢
      • 2021-02-24
      • 2015-12-21
      • 2021-05-08
      • 2018-04-27
      • 1970-01-01
      • 2013-03-19
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多