我正在尝试通过Netlify Lambda发送电子邮件,lambda在没有Mailjet集成的情况下可以顺利运行,并且我已经在节点测试脚本中尝试了Mailjet集成
const { MJ_USER, MJ_PASSWORD } = process.env;
const mailjet = require('node-mailjet').connect(MJ_USER, MJ_PASSWORD)
exports.handler = async (event, context) => {
if (event.httpMethod !== "POST") {
return { statusCode: 405, body: "Method Not Allowed" };
}
const data = JSON.parse(event.body)
const msg = { "Messages":[
{
"From": {
"Email": "sender@gmail.com",
"Name": "Paul"
},
"To": [
{
"Email": "receiver@gmail.com",
"Name": "Emma"
}
],
"TemplateID": 511035,
"TemplateLanguage": true,
"Subject": "Test mail",
"Variables": {
"input": "Test"
}
}
]}
mailjet.post("send", {'version': 'v3.1'}).request(msg)
.then((result) => {
return{ statusCode: 200, body: result.body}
}).catch((err) => {
return err
})
}
导致
{"errorMessage":"i is not a function","errorType":"TypeError","stackTrace":["n (/var/task/hello.js:1:220)","/var/task/hello.js:1:1019","Object.<anonymous> (/var/task/hello.js:1:1030)","Module._compile (module.js:652:30)","Object.Module._extensions..js (module.js:663:10)","Module.load (module.js:565:32)","tryModuleLoad (module.js:505:12)","Function.Module._load (module.js:497:3)","Module.require (module.js:596:17)"]}
该模块似乎无法正确加载,但我找不到解决方法
更新:
我在Netlify中找到了更多登录:
2:27:00 PM: Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
2:27:00 PM: @ /opt/build/repo/node_modules/formidable/lib/index.js
2:27:00 PM: @ /opt/build/repo/node_modules/superagent/lib/node/index.js
2:27:00 PM: @ /opt/build/repo/node_modules/node-mailjet/mailjet-client.js
2:27:00 PM: @ /opt/build/repo/node_modules/node-mailjet/index.js
2:27:00 PM: @ ./hello.js
错误的根本原因来自superagent
中的formidable
模块依赖关系,并且是由在netlify函数中使用webpack的babel转译引起的。
具体来说,可以在此处跟踪问题
if (global.GENTLY) require = GENTLY.hijack(require);
转译代码:
var require;if (global.GENTLY) require = GENTLY.hijack(!(function webpackMissingModule() { var e = new Error("Cannot find module ".""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
因此:
- 构建过程中
Critical dependency
警告 - 响应
Cannot find module.
错误
溶液:
使用问题中的临时修复程序,我们将为global.GENTLY
添加一个全局设置,因此 webpack 会将值设置为false
,而不注意行的其余部分。该行已确认仅用于测试目的。
创建一个文件来保存名为webpack.config.js
的额外 webpack 配置设置,并放入项目的根目录。
webpack.config.js
var webpack = require('webpack')
module.exports = {
plugins: [
new webpack.DefinePlugin({ "global.GENTLY": false })
]
}
现在更改函数的构建命令,以包含配置作为 webpack 的附加设置。
旧命令
netlify-lambda build <folder>
新建命令
netlify-lambda build <folder> -c webpack.config.js
如果一切顺利,则模块上不应出现警告或运行时故障。
注意:命令netlify-lambda
是 Netlify Lambda CLI 工具,用于帮助捆绑您的函数以进行 netlify 部署。如果您没有使用 CLI,那么您可以通过将插件添加到您的 webpack 配置来解决此问题。