react-native - 如何仅在 MacOS 上运行 npm postinstall 脚本
问题描述
如何将postinstall
脚本限制为仅在 macOS 上运行?
我的 React 本机库中有一个 shell 脚本,需要在 npm 安装完成后启动它。
这很好用,postinstall
但问题是 Windows 无法执行 shell 脚本。
"scripts": {
"postinstall": "./iospatch.sh"
},
我需要一种方法来限制它,只在 macOS 上运行。
我尝试使用这个库,但它不适用于我的情况 https://www.npmjs.com/package/cross-os
解决方案
对于跨平台,请考虑重新定义您的 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
选项设置为在子进程中为stdin、stdout、stderrinherit
配置管道。还要注意传递给
child_process.spawn()
is的命令sh
和参数是 shell 脚本的文件路径,即['./iospatch.sh']
. 我们这样做是为了避免必须在 macOS 上设置文件权限,以便它可以执行iospatch.sh
.
推荐阅读
- php - 将 PHPMailer 与 Slim 框架一起使用
- recursion - Clojure:在“IF”的两个条件下迭代循环
- xml - 如何使用 XPath 获取两个日期之间的秒数
- airflow - 如何管理具有不同开始日期的一百万个气流任务?
- api - 我无法在我的 cpanel 帐户上发布到 api
- ruby - NoMethod - 未定义的方法
即使方法已定义也会出错 - postgresql - 如何从 PostGIS 坐标中居中 openlayers 地图?
- flutter - How to create fade transition on push route flutter?
- opencv - 如何在段上应用ransac并绘制它们
- google-apps-script - How to increase i to next call?