私人回购依赖安装但 "Cannot Find Module"

Private repo dependency installs but "Cannot Find Module"

我有一个项目需要一个私人仓库作为依赖项。因此,projectA 将其作为 "projectB": "user/repo" 包含在 package.json 中。这安装得很好,并列在 projectA node_modules 中。问题是,该节点在我需要依赖项功能的地方抛出错误。错误是 "Cannot find module projectB"。如前所述,项目 B 列在 node_modules 中。这是项目 B 的结构:

.
├── README.md
├── file1.js
├── file2.js
├── file3.js
├── file4.js
└── package.json

它也有自己的 node_modules,但我将其排除在外。现在,file1.js 可能是这样的:

function getResult (a, b) {
  return a + b;
}

module.exports = { getResult }

这是项目 A 的样子:

var calculate = require('projectB').file1.getResult; // I've tried this in several other ways too

"Cannot find module error" 中调用计算结果。我是否在设置使用私人仓库作为依赖项时做错了根本性的错误 and/or 要求错误?

更新项目 B package.json

{
  "name": "projectB",
  "version": "1.0.0",
  "description": "Backend utility functions",
  "scripts": {
    "test": "mocha"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/user/repo.git"
  },
  "author": "Me",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com//user/repo/issues"
  },
  "homepage": "https://github.com//user/repo#readme",
  "dependencies": {
    "lodash": "^4.17.4",
    "mongodb": "^2.2.25",
    "redis": "^2.7.1",
    "winston": "^2.3.1"
  }
}

projectB 需要更新以设置合适的 main,但默认情况下将为 index.js。您可以执行以下操作:

// projectB/index.js
exports.file1 = require("./file1");
exports.file2 = require("./file2");
exports.file3 = require("./file3");
exports.file4 = require("./file4");

index.js 除了从库文件中导出外什么都不做,这实际上是一种非常常见的模式。