首页 > 解决方案 > 如何仅在 MacOS 上运行 npm postinstall 脚本

问题描述

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

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

这很好用,postinstall但问题是 Windows 无法执行 shell 脚本。

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

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

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

标签: react-nativenpmnpm-scriptspost-install

解决方案


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

"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选项设置为在子进程中为stdinstdoutstderrinherit配置管道。

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


推荐阅读