【问题标题】:How to run npm postinstall script only on MacOS如何仅在 MacOS 上运行 npm postinstall 脚本
【发布时间】:2021-11-22 04:58:51
【问题描述】:

如何将postinstall 脚本限制为仅在 macOS 上运行?

我的 React 本机库中有一个 shell 脚本,需要在 npm 安装完成后启动它。

这对 postinstall 很有效,但问题是 Windows 无法执行 shell 脚本。

"scripts": {
  "postinstall": "./iospatch.sh"
},

我需要一种方法来限制它,只在 macOS 上运行。

我尝试使用这个库,但它不适用于我的情况 https://www.npmjs.com/package/cross-os

【问题讨论】:

    标签: react-native npm npm-scripts post-install


    【解决方案1】:

    对于跨平台,请考虑重新定义您的 npm 脚本,如下所示。这可确保在 macOS 上安装软件包时,仅通过 postinstall npm 脚本运行 shell 脚本 (.sh)。

    "scripts": {
      "postinstall": "node -e \"process.platform === 'darwin' && require('child_process').spawn('sh', ['./iospatch.sh'], { stdio: 'inherit'})\""
    }
    

    说明:

    node -e \"...\" 部分利用 Node.js 命令行选项 -e 来评估内联 JavaScript,如下所示:

    • process.platform === 'darwin' 利用process.platform 属性来识别操作系统平台。如果它等于darwin,那么它就是 macOS。

    • && 运算符右侧的最后一部分;

      require('child_process').spawn('sh', ['./iospatch.sh'], { stdio: 'inherit'})
      

      仅当 && 运算符左侧的表达式为 true 时才执行,即仅在平台为 macOS 时运行。

      这部分代码本质上是利用child_process.spawn() 方法来调用您的.sh 文件。 stdio 选项设置为inherit 以在子进程中为 stdinstdoutstderr 配置管道。

      还要注意传递给child_process.spawn() 的命令是sh,参数是shell 脚本的文件路径,即['./iospatch.sh']。我们这样做是为了避免在 macOS 上设置文件权限,以便它可以执行 iospatch.sh

    【讨论】:

    • 我建议可以将 postintall comamnd 中的“逻辑”放入 postinstall 脚本文件本身。如果平台是 macOS,您可以检查 iospatch.sh,如果为 false,则退出。
    • @psimms - 确实,但是这种方法假定操作系统试图执行 .sh 文件可以解释一个 shell 脚本 - 例如,旧的 Windows 不能。因此,对于跨平台支持,最好通过 Node.js 处理检查。
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    相关资源
    最近更新 更多