导出未在 ES 模块范围 AWS Lambda 中定义

exports is not defined in ES module scope AWS Lambda

我正在尝试使用 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"
  ]
}

I have removed the type: module and used require instead of import, but I keep getting the same problem.

Lambda 文件夹结构(节点 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"
  }
}

因为你有 "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