繁体   English   中英

Heroku + Node:找不到模块错误

[英]Heroku + Node: Cannot find module error

我的 Node 应用程序在本地运行良好,但在部署到 Heroku 时遇到了错误。 该应用程序在/models文件夹中使用 Sequelize,其中包含index.jsCompany.jsUsers.js 在本地,我可以使用/models/index.js的以下代码导入模型:

// load models
var models = [
  'Company',
  'User'
];
models.forEach(function(model) {
  module.exports[model] = sequelize.import(__dirname + '/' + model);
});

这工作正常,但是,当我部署到 Heroku 时,应用程序崩溃并显示以下错误:

Error: Cannot find module '/app/models/Company'
   at Function.Module._resolveFilename (module.js:338:15)
   at Function.Module._load (module.js:280:25)
   at Module.require (module.js:364:17)
   at require (module.js:380:17)
   at module.exports.Sequelize.import (/app/node_modules/sequelize/lib/sequelize.js:219:24)
   at module.exports.sequelize (/app/models/index.js:60:43)
   at Array.forEach (native)
   at Object.<anonymous> (/app/models/index.js:59:8)
   at Module._compile (module.js:456:26)
   at Object.Module._extensions..js (module.js:474:10)
Process exited with status 8

最初我认为这是由于区分大小写(本地 mac 与 heroku linux),但我移动了文件,进行了 git 提交,然后移回并再次提交以确保Company.js在 git 存储库中大写。 这并没有解决问题,我不确定问题可能是什么。

问题是由于区分大小写和文件命名。 Mac OS X 不区分大小写(但知道),而 Heroku 基于 Linux 并且区分大小写。 通过从我的终端运行heroku run bash ,我能够看到/models文件夹如何出现在 Heroku 的文件系统上。 解决方案是将本地系统上的User.jsCompany.js重命名为新的临时文件,将更改提交到 git,然后重命名回User.jsCompany.js ,注意首字母大写,然后提交更改再次通过git。 以前我曾尝试将文件直接从user.js重命名为User.js ,将company.js重命名为Company.js但 git commit 和区分大小写的文件名更改并未反映在 Heroku 上。

我看不到确切的修复方法,但是您可以通过运行heroku run bash登录到 Heroku 实例,然后运行node以输入 REPL,并尝试直接要求路径来自己解决。

对我来说,这是由我不小心包含在 .gitignore 中的文件夹引起的!

我遇到过这样的错误,原因是我将模块module.js重命名为Module.js并且 Heroku 缓存与名称冲突。 您必须禁用模块缓存以避免此类错误:

$ heroku config:set NODE_MODULES_CACHE=false

来源: https : //help.heroku.com/TO64O3OG/cannot-find-module-in-node-js-at-runtime

我的一个文件在本地有一个小写名称,需要小写。

const Product = require('../models/product');

在 git repo 上,它被大写。

'../models/Product'

服务器试图请求一个不存在的文件。 我不得不使用git mv在本地重命名文件,然后重新上传它以解决问题。

不确定这是否与此处描述的问题相同,但对我而言,我的require("dotenv").config()不是以代码运行的环境为条件的,因此 Heroku 无法找到它,因为它安装为一个devDependency

修复:

if (process.env.NODE_ENV !== "production") {
  require("dotenv").config();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM