module.js 在 运行 iron-node 时找不到模块

module.js cannot find modules when running iron-node

我正在尝试使用 iron-node (v2.2.17) 来调试我的 mocha 单元测试。当我从我的 package.json:

运行 这个命令时,单元测试 运行 很好
"test": "cross-env NODE_ENV=test mocha test/.setup.js --reporter progress --compilers js:babel-core/register --require babel-polyfill --recursive \"./src/**/*.spec.js\" \"./src/**/*.integrationSpec.js\" \"./test/**/*.spec.js\"",

但是当我运行这个命令时测试失败:

"debug:test": "cross-env NODE_ENV=test iron-node node_modules\mocha\bin\_mocha test/.setup.js --reporter progress --compilers js:babel-core/register --require babel-polyfill --recursive \"./src/**/*.spec.js\" \"./src/**/*.integrationSpec.js\" \"./test/**/*.spec.js\"",

控制台中的错误是:

Error: Cannot find module 'src/framework/api/entityAddresses/entityAddressesAc  tions'

  - module.js:16 require
    internal/module.js:16:19

  - entityAddressesActions.spec.js:5 Object.<anonymous>
    entityAddressesActions.spec.js:5:1

此模块位于 C:\TFS\Dev-UI\WebApp\Src\Web\Web\src\framework\api\entityAddresses\entityAddressesActions.js

我的项目文件夹是C:\TFS\Dev-UI\WebApp\Src\Web\Web,我的process.env.NODE_PATH也是C:\TFS\Dev-UI\WebApp\Src\Web\Web。 (它是未定义的,但我在 .iron-node.js 中将其设置为 process.cwd() - 参见 https://github.com/s-a/iron-node/issues/98#issuecomment-218658236

我不知道为什么找不到模块。我是否缺少某些配置?

编辑

这个 SO 答案建议在应用程序启动后设置 process.env.NODE_PATH 将不起作用,因为模块路径已缓存:Determine project root from a running node.js application

我不知道如何在 iron-node 启动之前设置它,它总是未定义

可以使用 .iron-node.js 配置文件解决问题:

process.env.NODE_PATH = process.cwd(); // fix problem where modules are not resolved - Jack Allan.
var path = require("path");
var settings = {
  "nodeModule" : {
     "scriptInjection" : "module.paths.push(process.env.NODE_PATH);",  // fix problem where modules are not resolved - Jack Allan.
  },
  "v8": {
    "flags" : [                             // DEFAULT=[]; https://github.com/thlorenz/v8-flags/blob/master/flags-0.11.md
    ]
  },
  "app": {
    "native+"               : false,   // DEFAULT=FALSE; extends require to search native modules respecting the current v8 engine version.
    "autoAddWorkSpace"      : false,  // DEFAULT=TRUE; disables the autoAddWorkSpace behavior.
    "openDevToolsDetached"  : false,  // DEFAULT=FALSE; opens the dev tools windows detached in an own window.
    "hideMainWindow"        : false,  // DEFAULT=FALSE;  hides the main window to show dev tools only.
  },
  "workSpaceDirectory"        : function(argv) {  // determines the workspace directory for specific commandline applications.
    var result = "";
    if (argv[2]){
      result = path.dirname(argv[2]);
      var startupScriptName = path.basename(argv[2]).toLowerCase();

      switch(startupScriptName) {
          case "_mocha":
            result = process.cwd();
            break;
          default:
            result = path.resolve(result);
            break;
      }
    }

    return result;
  }
};

module.exports = settings;

感谢 s-a 的建议:https://github.com/s-a/iron-node/issues/98#issuecomment-218712907