node.js - 从子目录运行父 npm 脚本时如何找到原始目录?

标签 node.js npm

我有一个相当标准的 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)。

我的主要用例是过滤测试以仅运行当前子目录中的测试,因此添加单独的脚本来为每个子目录运行是不切实际的。

最佳答案

来自npm docs:

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/

相关文章:

node.js - 在 npm 中将工件上传到 nexus

javascript - 将 json 拆分为轮播卡

javascript - 'this' 在子类中未定义

node.js - React Native require(moduleName) 如何工作?

node.js - 如何从 lowdb 进行查询以返回给定范围内的结果?

macos - 如何修复 "zsh: command not found: vue"?

node.js - 为什么 execSync 在我的代码中不起作用?

node.js - create-react-app my-app ...找不到命令

node.js - 无法在某个范围内安装 NPM 包,或者无法在范围内安装 NPM 包(或者看起来像这样)

node.js - Plesk 如何安装附加模块?