首页 > 解决方案 > NPM 脚本条件不适用于 Windows,但适用于 Linux 和 Mac

问题描述

下面的 NPM 脚本在 Linux 和 MacOS 上运行良好,但在 Windows 上不运行。我试图寻找一些解决方案,但找不到一个!

"scripts": {
        "install-dependencies": "if [ ! -d node_modules ]; then npm install && npx npm-install-peers; fi",
},

我得到的错误是:

> if [ -d node_modules ==false ]; then npm install && npx npm-install-peers; fi

-d was unexpected at this time.
npm ERR! code ELIFECYCLE
npm ERR! errno 1

有什么方法可以使它在 Windows 系统上也能正常工作?

标签: npmnpm-scripts

解决方案


Windows 命令行不等同于其他系统上的 bash。您将需要通过某种方式安装 bash(例如 git 为 windows 附带的 bash),并在该 shell 中调用 npm。

这个包也是相关的,但同样不能解决问题:https ://www.npmjs.com/package/cross-env

评论的跟进。Node.js已经兼容该代码需要运行的任何地方。所以我建议在 npm script 命令中只使用 node 来运行脚本。

{
  "install-dependencies": " node -e 'process.exit(require(`fs`).existsSync(`node_modules`) ? 0 : 1)' && echo 'succ'"
}

推荐阅读