在 ES 模块范围内,AWS Lambda 中未定义 exports。

15

我正在尝试使用JavaScript模块执行以下代码。我知道NodeJS的默认是CommonJS。我已经在本地使我的代码工作,但是当我想在lambda中将其作为模块运行时,我遇到了以下问题:

错误:

{
  "errorType": "ReferenceError",
  "errorMessage": "exports is not defined in ES module scope\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.",
  "trace": [
    "ReferenceError: exports is not defined in ES module scope",
    "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/index.js:2:1",
    "    at ModuleJob.run (node:internal/modules/esm/module_job:195:25)",
    "    at async Promise.all (index 0)",
    "    at async ESMLoader.import (node:internal/modules/esm/loader:337:24)",
    "    at async _tryAwaitImport (file:///var/runtime/index.mjs:660:16)",
    "    at async _tryRequire (file:///var/runtime/index.mjs:709:37)",
    "    at async _loadUserApp (file:///var/runtime/index.mjs:721:16)",
    "    at async Object.module.exports.load (file:///var/runtime/index.mjs:741:21)",
    "    at async file:///var/runtime/index.mjs:781:15",
    "    at async file:///var/runtime/index.mjs:4:1"
  ]
}

我已经移除了 type: module,并使用 require 替换了 import,但我仍然遇到了相同的问题。 Lambda 文件夹结构 (Node V16.X):
+SendPushNotification(root)
 +node_modules
 -index.js
 -package.json
 -package.json.lock

INDEX.JS

import * as OneSignal from '@onesignal/node-onesignal';

exports.handler = async (event) => {
    const response = "hey";
    console.log("testing")
    
    return response;
};

PACKAGE.JSON

{
  "name": "onesignal-nodejs-client-sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module"
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@onesignal/node-onesignal": "^1.0.0-beta4"
  }
}
1个回答

28

由于您设置了"type": "module",启用了ES6模块化。 您应该将index.js更改为

import * as OneSignal from '@onesignal/node-onesignal';

export const handler = async (event) => {
    const response = "hey";
    console.log("testing")

    return response;
};

如果你想要一个默认的导出,请使用:

import * as OneSignal from '@onesignal/node-onesignal';
const handler = async (event) => {
    const response = "hey";
    console.log("testing")

    return response;
};

export default handler

4
如果我选择第二个选项,我会得到这个错误:"errorMessage": "index.handler is undefined or not exported",但第一个选项可以正常工作。 - Patricio Vargas
2
如果您将函数导出为默认值,则应将其作为import handler from 'index.js'导入,并将其用作handler()而不是index.handler()。 - Pishameni
1
无缝地与 AWS-cognito-PreSignUp lambda 协同工作。 - Sudarshan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接