Home > OS >  exports is not defined in ES module scope AWS Lambda
exports is not defined in ES module scope AWS Lambda

Time:05-25

I'm trying to execute the following code using JavaScript modules. I know that the default for NodeJS is CommonJS. I have my code working locally, but when I want to run it as modules in the lambda and I'm running into the following issue:

ERROR:

{
  "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 Folder Structure (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"
  }
}

CodePudding user response:

Since you have "type": "module", ES6 modules are enabled. You should change index.js to

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

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

    return response;
};

And, if you want a default export, use:

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

    return response;
};

export default handler
  • Related