如何让npm的postinstall脚本仅在macOS系统下执行
解决方案
你可以通过以下几种无额外依赖的方式实现仅在macOS下执行postinstall脚本:
方案1:直接在npm脚本内嵌入系统判断(推荐,无需新增文件)
直接修改package.json的scripts配置,利用Node.js内置的API判断系统类型,仅当识别到macOS(darwin内核)时执行shell脚本:
"scripts": { "postinstall": "node -e \"process.platform === 'darwin' && require('child_process').execSync('./iospatch.sh', { stdio: 'inherit' })\"" },
该方案兼容所有主流npm版本,Windows/Linux环境下会直接跳过脚本执行,不会报错。
方案2:单独写执行入口脚本(更易维护)
如果需要增加额外逻辑、错误处理,可以新建独立的JS执行入口:
- 在项目根目录新建
postinstall.js,内容如下:
const { execSync } = require('child_process'); const os = require('os'); if (os.platform() === 'darwin') { try { execSync('./iospatch.sh', { stdio: 'inherit' }); } catch (err) { console.error('iOS patch 脚本执行失败:', err.message); process.exit(1); } }
- 修改package.json的scripts配置:
"scripts": { "postinstall": "node postinstall.js" },
注意事项
- 确保
iospatch.sh文件有可执行权限,可在提交代码前执行chmod +x iospatch.sh添加权限 - 如果脚本路径不是根目录,需要对应修改配置中的路径参数
内容的提问来源于stack exchange,提问作者Aleksandar Marinkovic
相关产品推荐
相关产品推荐

