更改 npm 脚本的工作目录

Change working directory for npm scripts

问:是否可以更改 npm 运行脚本的上下文?

我想要的是:

"scripts": {
   "test": "gulp mocha",
   "pre-install": "./deps/2.7/cpython/configure --prefix=$(pwd)/build --exec-prefix=$(pwd)/build && make -C deps/2.7/cpython && make -C deps/2.7/cpython install",
   "install": "node-gyp rebuild"
},

显然 cd deps/2.7/cpython/ && ./configure 可以在类 UNIX 系统上运行,但不能在 windows 上运行。

原因: 问题的根源在于,python 存储库的 configure 命令将文件输出到调用它的目录中。然而,这些文件与 makemake install 相关,它们在 repo 目录中查找文件。

在这种情况下,我无法更改 Makefile,因为 Python 的构建过程非常复杂。

替代方案:替代方案可能是写一些install.js并使用节点的OS独立API和一些child_process.exec() ,我可能会这样做。但是,不离开 npm 真的很好。

如上所述:

npm is probably using

var spawn = require('child_process').spawn

which would allow you to set options like:

    {cwd: pwd + 'somepath'}

but isn't exposing it.

I've solved it with a fairly large install.js, which does roughly that and it gets called from package.json like above. The API of child_process isn't that easy to handle, though, since it throws loads of hard to debug errors. Took me some time, but I am happy now.

npm 只允许做 cd dir && command -args,这也会在 Windows 上做 运行。

已在 PR https://github.com/npm/npm/pull/10958 中更改使用 node 的生成功能,但由于上述解决方案而被拒绝。

尝试

 const { execSync } = require('child_process');

 execSync(`cd ${your_working_directory} && npm install`)