我有一个像这样的package.json:
...
"scripts": {
"dev": "webpack --config webpack.dev.config.js --mode development --progress --colors",
"postdev": "if (Test-Path \"./postdev.sh\" ) { echo \"file exists\"; ./postdev.sh }"
},
...
如何检查文件“postdev.sh”是否存在,然后在 NPM 脚本部分启动它? 我在终端中运行该命令并且运行正常,但如果我尝试启动该 npm 脚本,它会显示“意外出现:“./postdev.sh”。”
在 Macos 或 Linux 上尝试这个 postdev:
"postdev": "test -f ./postdev.sh && echo 'file exisits' && ./postdev.sh",
path-exists-cli
包来检查文件/目录是否存在,并在存在或不存在时使用&&
或||
分别运行下一个命令:
{
"scripts": {
// other scripts...
"postdev": "path-exists ./postdev.sh && echo 'Exists' || echo 'Does not exists'"
}
}
终于找到了解决方案(也许只适用于Windows,但对我来说已经足够了):
"postdev": "if exist postdev.sh ( postdev.sh )",
我想说
smth && script
或smth && script || :
都不是好的解决方案。当 smth
失败时,第一个仍然失败,并且您将无法忽略不存在的文件情况。第二个不好,因为你忽略了 smth
和 script
一起失败。
我更喜欢在这里使用 shell 脚本:
"postinstall": "sh -c 'if [ -f ./dist/postinstall.js ]; then node ./dist/postinstall.js; fi'"
当我们有
dist
文件夹时,它会运行安装后操作,并且不会忽略安装后脚本失败。
谢谢你。