我已经尝试了在这里和其他论坛上可以找到的所有方法,使用常见的 JS 和 ES 模块导出/导入节点函数。即使使用最简单的导入,我也会收到 Lambda 抛出的无用错误:
回应 { "errorType": "运行时.UserCodeSyntaxError", "errorMessage": "SyntaxError: 意外的标识符", “痕迹”: [ “Runtime.UserCodeSyntaxError:SyntaxError:意外的标识符”, 在 _loadUserApp (文件:///var/runtime/index.mjs:1058:17)", 在异步 UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1093:21)", 在异步启动时(file:///var/runtime/index.mjs:1256:23)”, 在异步文件:///var/runtime/index.mjs:1262:1” ] }
主要功能index.mjs:
export const handler = async (event) => {
import test_module from "./node_modules/test_module.mjs";
const result = test_module();
const response = {
statusCode: 200,
body: result,
};
return response;
};
./node_modules/test_module.mjs 中的模块函数:
export const test_module = async() => {
return "Hello from module."
}
背景:
我使用导出和要求在本地运行了一些 Nodejs 代码,没有错误。看起来 Lambda 想要使用 .mjs 文件和 ES 模块语法,因此我尝试将所有导入更改为使用导出和导入。我在论坛中发现了一些不同的语法。都尝试过。尝试使用index.mjs“./”根目录中和node_modules子目录中的文件。还尝试使用 package.json 指向 node_modules 目录。该错误并没有表明问题出在 import 语句中,但如果我注释掉 import 并在 index.mjs 中设置结果 const ,它就可以工作。因此,出于某种原因,Lambda 不喜欢 import 语句。请帮忙。
解决了。 ES 模块导入语句需要位于函数外部的顶层。例如。这有效。
// index.mjs
// Note: ES module import syntax at top level (not in handler)
import { test_module } from "./node_modules/test_module.mjs";
// Now the function
export const handler = async (event) => {
const parameter = await test_module("Test Input"); // call the function in the module
const response = {
statusCode: 200,
body: parameter,
};
return response;
};
//test_module.mjs in "node_modules" subdirectory
export const test_module = async(input) => {
return "Hello from module." + input;
};