更改 npm 脚本的工作目录

问: 是否可以改变 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 repo 的 configure命令将文件输出到调用它的目录中。然而,这些文件是构建与 makemake install相关的,它们在回购目录中查找文件。

在这种情况下,我不能更改 Makefile,因为 Python 的构建过程是可以理解的复杂的。

替代方案: 替代方案可能是编写一些 install.js并使用节点独立于操作系统的 API 和一些 child_process.exec(),我可能会这样做。然而,不离开 Npm将是非常好的。

76946 次浏览

As noted above:

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 allows only to do cd dir && command -args, which will also run on Windows.

A change to use node's spawn functionality has been made in PR https://github.com/npm/npm/pull/10958, but was rejected, due to the above solution.

try

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


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