jgood2
jgood2

Reputation: 1

AWS Lambda NodeJS 18.x function, simple ES module import throws Runtime.UserCodeSyntaxError

I've tried all of the approaches I could find here and on other forums for export / import of node functions using common JS and ES modules. Even with the simplest of imports I get this unhelpful error thrown from Lambda:

Response { "errorType": "Runtime.UserCodeSyntaxError", "errorMessage": "SyntaxError: Unexpected identifier", "trace": [ "Runtime.UserCodeSyntaxError: SyntaxError: Unexpected identifier", at _loadUserApp (file:///var/runtime/index.mjs:1058:17)", at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1093:21)", at async start (file:///var/runtime/index.mjs:1256:23)", at async file:///var/runtime/index.mjs:1262:1" ] }

Main function index.mjs:

export const handler = async (event) => {

   import test_module from "./node_modules/test_module.mjs";

   const result = test_module();

   const response = {
      statusCode: 200,
      body: result,    
   }; 
   return response; 
};

Module function in ./node_modules/test_module.mjs:

export const test_module = async() => {    
    return "Hello from module." 
}

Background:

I had some Nodejs code running without error locally using exports & require. It looks like Lambda wants to use .mjs files and ES modules syntax, so I tried to change all of my imports to use export and import. I found a few different syntaxes in forums. Tried them all. Tried with the files in the root with index.mjs "./" and in node_modules sub-directory. Also tried using the package.json to point to node_modules directory. The error doesn't indicate anything to say the problem is in the import statement but if I comment out the import and and set the result const within index.mjs it works. So Lambda doesn't like the import statement for some reason. Please help.

Upvotes: 0

Views: 2267

Answers (1)

jgood2
jgood2

Reputation: 1

Solved. The ES module import statement needs to be at the top level, outside of the function. E.g. This works.

// index.mjs

// Note: ES module import syntax at top level (not in handler)
import { test_module } from "./node_modules/test_module.mjs"; 

// Now the function
export const handler = async (event) => {
    const parameter = await test_module("Test Input"); // call the function in the module
    const response = {
        statusCode: 200,
        body: parameter,
    };
    return response;
};


//test_module.mjs in "node_modules" subdirectory
export const test_module = async(input) => {
    return "Hello from module." + input;
};

Upvotes: 0

Related Questions