首页 > 解决方案 > AWS SAM 本地启动 API:设置 lambda nodejs 12.x 标志(例如 --experimental-modules)?

问题描述

我在我的 nodejs 服务器上使用 ES6 模块语法:

包.json

"type": "module"

我(成功)将我的服务器作为本地 nodejs 进程运行。例如:

"scripts": {
  "dev": "npm outdated ; nodemon --experimental-modules --inspect=4001 main.local.js"
}

问题:如果我通过 sam local 启动我的服务器:

"scripts": {
  "dev-sam": "sam local start-api --skip-pull-image",
}

我收到一个错误:

Warning: require() of ES modules is not supported. 
require() of /var/task/main.js from /var/runtime/UserFunction.js is an ES module file 
as it is a .js file whose nearest parent package.jsoncontains "type": "module" which 
defines all .js files in that package scope as ES modules.
Instead rename main.js to end in .cjs, change the requiring code to use import(), or 
remove "type": "module" from /var/task/package.json.

我的结论是:我需要告诉 nodejs 运行时启用实验性 es6 模块支持。

问题:我该怎么做?

试过(不工作):

"scripts": {
  "dev-sam": "sam local start-api --experimental-modules --skip-pull-image",
}

标签: javascriptnode.jsaws-lambdaes6-modulesaws-sam-cli

解决方案


您不能将参数传递给 lambda 环境。您需要使用转译器。使用 webpack 或类似的编译器编译你的 lambda 函数。


推荐阅读