在 webpack npm 脚本中启动文件之前检查文件是否存在

问题描述 投票:0回答:4

我有一个像这样的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”。”

node.js windows npm webpack npm-scripts
4个回答
3
投票

在 Macos 或 Linux 上尝试这个 postdev:

"postdev": "test -f ./postdev.sh && echo 'file exisits' && ./postdev.sh",

3
投票

您可以使用跨平台工具

path-exists-cli
包来检查文件/目录是否存在,并在存在或不存在时使用
&&
||
分别运行下一个命令:

{
  "scripts": {
    // other scripts...
    "postdev": "path-exists ./postdev.sh && echo 'Exists' || echo 'Does not exists'"
  }
}

2
投票

终于找到了解决方案(也许只适用于Windows,但对我来说已经足够了):

"postdev": "if exist postdev.sh ( postdev.sh )",

0
投票

我想说

smth && script
smth && script || :
都不是好的解决方案。当
smth
失败时,第一个仍然失败,并且您将无法忽略不存在的文件情况。第二个不好,因为你忽略了
smth
script
一起失败。

我更喜欢在这里使用 shell 脚本:

"postinstall": "sh -c 'if [ -f ./dist/postinstall.js ]; then node ./dist/postinstall.js; fi'"

当我们有

dist
文件夹时,它会运行安装后操作,并且不会忽略安装后脚本失败。

谢谢你。

© www.soinside.com 2019 - 2024. All rights reserved.