javascript - ImportModuleError","errorMessage":"错误:在使用具有依赖关系的 Netlify lambda 函数时找不到模块
问题描述
我正在尝试使用 netlify 及其 lambda 函数功能来运行具有依赖关系的节点函数。基于https://css-tricks.com/using-netlify-forms-and-netlify-functions-to-build-an-email-sign-up-widget/,我有我的函数/submission-created.js :
const fetch = require('node-fetch');
exports.handler = async event => {
const email = JSON.parse(event.body).payload.EMAIL
const asking = JSON.parse(event.body).payload.ASKING
console.log(`Recieved a submission: ${email}`)
....
当我查看我的 netlify 网站功能选项卡(上面的截图)时,我看到:
11:40:35 PM: 2020-12-02T04:40:35.092Z undefined ERROR Uncaught Exception {"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'node-fetch'\nRequire stack:\n- /var/task/submission-created.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js","stack":["Runtime.ImportModuleError: Error: Cannot find module 'node-fetch'","Require stack:","- /var/task/submission-created.js","- /var/runtime/UserFunction.js","- /var/runtime/index.js"," at _loadUserApp (/var/runtime/UserFunction.js:100:13)"," at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)"," at Object.<anonymous> (/var/runtime/index.js:43:30)"," at Module._compile (internal/modules/cjs/loader.js:1015:30)"," at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)"," at Module.load (internal/modules/cjs/loader.js:879:32)"," at Function.Module._load (internal/modules/cjs/loader.js:724:14)"," at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)"," at internal/main/run_main_module.js:17:47"]}
我的 package.json (运行 npm init 之后):
{
"name": "site",
"version": "1.0.0",
"description": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^8.2.0",
"node-fetch": "^2.6.1"
}
}
包结构如下:
这是回购:
https://github.com/kc1/test2
我尝试将节点模块文件夹和 package.json 放在多个位置并重新推送存储库,但我仍然收到上述错误。我究竟做错了什么?
编辑:
请参阅Netlify:未找到构建命令,继续发布有关构建过程的新信息
解决方案
我认为这个错误有很多原因,我今天得到它并尝试了一些解决方案Error: Cannot find module 'node-fetch'" when deploying function ; Netlify 函数找不到模块;并且不能在 lambda 函数中使用 node-fetch
- 在项目根目录中安装依赖项
- 在特定于功能的文件夹中安装 deps,例如
functions/testfunc/package.json
将命令更改netlify.toml
为cd functions/testfunc && npm install && cd ../../ && npm build
- 将 const 更改
fetch = require('node-fetch')
为:const fetch = require('node-fetch').default
const fetch = request('node-fetch').default
- 添加
node-fetch
的对等依赖项encoding
然而,这些都没有奏效。然后,我尝试查看从 Netlify 函数游乐场复制Fetch示例是否可行,并且确实可行。问题是我的函数中有一个名为static
const static = ['/blog', '/about', '/'];
由于某种原因,有一个称为静态原因的变量
Error: Cannot find module 'node-fetch'
我不知道为什么,但是将其更改为其他内容可以解决此问题。