在 aws lambda 和无服务器上使用 esmodules 获取“ES 模块范围中未定义 require”

问题描述 投票:0回答:1

我正在尝试通过nodejs、无服务器并使用es模块在aws lambda上开发脚本

我一直收到这个错误:

{
    "errorType": "ReferenceError",
    "errorMessage": "require is not defined in ES module scope, you can use import instead\nThis file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains \"type\": \"module\". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.",
    "stack": [
        "ReferenceError: require is not defined in ES module scope, you can use import instead",
        "This file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains \"type\": \"module\". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.",
        "    at file:///var/task/s_getStatus.js:2:21",
        "    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)"
    ]
}

我知道某个地方的脚本仍然使用 commonjs 样式代码,但在本地找不到它。当使用无服务器离线运行时,也没有问题(代码正在运行)。

我的处理程序代码很简单:

export default async function () {
  return {
    statusCode: 200,
    body: JSON.stringify({ status: true }),
  };
}

主脚本(handler.js)的代码是:

'use strict';

export {default as getStatus} from './handlers/get_status/index.js';

我的package.json是:

{
  "name": "...-api",
  "version": "1.0.0",
  "main": "handler.js",
  "repository": "...-api.git",
  "type": "module",
  "private": true,
  "scripts": {
    "local": "sls offline",
  },
  "dependencies": {
    "@aws-sdk/client-kms": "3.348.0",
    "serverless-plugin-tracing": "2.0.0"
  },
  "devDependencies": {
    ...
    "serverless-offline": "12.0.4",
    "serverless-prune-plugin": "2.0.2"
  }
}

我的无服务器文件:

org: mathkr
app: healthcheck-api
service: healthcheck-api
frameworkVersion: '3'
useDotenv: true
provider:
  name: aws
  runtime: nodejs18.x
  region: eu-west-3
  tracing:
    lambda: true
  iamRoleStatements:
    - Effect: Allow
      Action:
        - xray:PutTraceSegments
        - xray:PutTelemetryRecords
      Resource:
        - '*'
plugins:
  - serverless-plugin-tracing
functions:
  getStatus:
    handler: handler.getStatus
    timeout: 30
    events:
      - http:
          path: /status
          method: get
          cors: false

没什么疯狂的。我认为,重点在于错误的“var/task/s_getStatus.js:2:21”部分。似乎某处使用某些东西需要指令,但是什么?似乎在 package.json 文件中,指令 type: 'module' 定义良好。所以我不明白我错过了什么......

无服务器正在将代码转换为 commonjs 吗?我是否忘记在某个地方设置告诉使用 esm 的选项?

node.js aws-lambda serverless es6-modules
1个回答
0
投票

由于您在

app
文件中使用
org
serverless.yml
键,因此它使用无服务器仪表板插件进行部署。

不幸的是,这个插件没有 ESM 支持,因此使用

require()
语句。

目前,Serverless Dashboard 没有支持 ESM 的计划。参考:https://github.com/serverless/dashboard-plugin/issues/564

所以你有几个选择:

  1. 删除无服务器仪表板(因为它已被弃用)。您可以通过从
    app
    文件中删除
    org
    serverless.yml
    键来完成此操作。
  2. 从 Serverless Dashboard 迁移到 Serverless Console,后者已经支持 ES 模块。
  3. 使用 CommonJS(而不是 ES 模块)重写应用程序逻辑。
© www.soinside.com 2019 - 2024. All rights reserved.