node.js - 为运行二进制文件的 NPM 脚本设置 CWD

标签 node.js npm npm-scripts working-directory

我有一个 super 项目,它托 pipe 项目并包含常见的依赖项:

super
  node_modules
    .bin
      foo-binary
      foo-binary.exe
    foo
  sub
    node_modules
    package.json
  package.json

我需要能够调用foo要么为 super NPM 脚本:

super/package.json

"scripts": {
  "foo": "foo-binary" <-- should run with super/sub/ as CWD
}

在本例中foo-binary运行 super/作为 CWD,而它应该以 super/sub/ 运行。使用cd导致跨平台问题; cd sub && ..\\node_modules\\.bin\\foo-binary带有反斜杠的适用于 Windows,但不适用于 *nix 操作系统,而 cd sub && ../node_modules/.bin/foo-binary使用正斜杠在 Windows 上失败(在 Windows 7 上测试):

".." is not recognized as an internal or external command, operable program or batch file

或者我需要能够调用foo要么为 super NPM 脚本:

super/sub/package.json

"scripts": {
  "foo": "../node_modules/.bin/foo-binary"
}

在这种情况下,特定于平台的路径在 Windows 上也会失败。

sub 有几个原因不能有foo作为其自身的依赖项,其中之一是所有子项目应一致使用相同的 foo版本且不占用空间多个foo副本。

在这种情况下如何设置当前工作目录,跨平台并且最好不向项目添加自定义脚本?

最佳答案

用 JSON 转义双引号将 npm 脚本中定义的路径括起来,即 \"...\"

例如:

"scripts": {
  "foo": "cd sub && \"../node_modules/.bin/foo-binary\""
}

现在将通过 windows cmd.exe 和 *nix sh 成功跨平台运行。

关于node.js - 为运行二进制文件的 NPM 脚本设置 CWD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55664753/

相关文章:

javascript - 如何使用 sequelize beforeCreate 自动生成 Id 值?

npm - 为什么我在执行 npm install 时会看到这个

npm - 将 postcss 与 autoprefixer 一起使用并收到错误 - 'cannot find module'

node.js - 如何将 Powershell 命令添加到 NPM 脚本?

javascript - “发送到客户端后无法设置 header ” - 我正在设置 header ,但找不到位置

javascript - 批量 REST API POST 处理

node.js - 在防火墙后面使用 npm

node.js - 如何防止安装未使用的 npm 依赖项?

npm - 如何从 npm "postinstall" Hook 获取包名称?

node.js - 使用 mongoose Schema.methods 函数运行应用程序时出错