【问题标题】:Private repo dependency installs but "Cannot Find Module"私人仓库依赖安装但“找不到模块”
【发布时间】:2017-03-30 03:20:46
【问题描述】:

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

.
├── 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 }

这是 projectA 的样子:

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

"Cannot find module error" 中调用计算结果。在设置使用私有仓库作为依赖项和/或要求它错误时,我是否做错了什么?

更新 projectB 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"
  }
}

【问题讨论】:

  • package.json 对应于 projectB 是什么样的?它需要声明一个main,除非它有index.js
  • 更新帖子,如果这只是一堆辅助函数,main.js 会是什么样子?

标签: node.js package.json


【解决方案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 实际上是一种非常常见的模式,除了从库文件中导出之外什么都不做。

【讨论】:

  • 谢谢。有趣的是,我是这样开始的,然后认为这是一个不必要的步骤,然后将其删除。显然不是!
猜你喜欢
  • 2021-11-04
  • 1970-01-01
  • 2018-12-27
  • 2016-11-02
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多