我有一个相当标准的 Web 应用程序结构,它使用 npm 来执行一些 node.js 测试脚本。此外,npm 允许您从子目录执行父包脚本。
举个例子:
|-- my-app
| |-- package.json
| |-- test-script.js
| |-- component-one
| | |-- test-one.spec.js
| |-- component-two
| | |-- test-two.spec.js
> /my-app/component-one: npm run test
# Runs test-script.js as specified in root package's scripts
我希望能够确定运行脚本的原始子文件夹。但是,我一直无法找到访问该目录的方法。 process.cwd()
和 __dirname
都返回脚本的父级目录位置(示例中的my-app)。
我的主要用例是过滤测试以仅运行当前子目录中的测试,因此添加单独的脚本来为每个子目录运行是不切实际的。
最佳答案
Scripts are run from the root of the module, regardless of what your current working directory is when you call npm run. If you want your script to use different behavior based on what subdirectory you’re in, you can use the
INIT_CWD
environment variable, which holds the full path you were in when you ran npm run.
来自 pull request: 的文档
npm run
将当前工作目录添加到 INIT_CWD
。您可以在项目的子目录中运行脚本。例如,您想在特定子目录中运行 babel。你应该写:
"scripts": {
"build": "babel $INIT_CWD/src -d $INIT_CWD/lib"
}
或者你可以写:
"scripts": {
"build": "cd $INIT_CWD && babel src -d lib"
}
现在,您可以在任何要编译 JavaScript 的子目录中运行脚本 npm run build
。在您的情况下,您可能需要将 cwd 作为参数传递给脚本并覆盖 INIT_CWD
var。
关于node.js - 从子目录运行父 npm 脚本时如何找到原始目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56719591/