Search code examples
node.jsamazon-web-servicesaws-lambda

How to solve -Cannot use import statement outside a module in AWS lambda console


I am trying this in the AWS lambda console. I have installed npm install @aws-sdk/client-kinesis on my terminal and used zipped the file and created a lambda layer which has client-kinesis.

If use the following it works!

 // ES5 example
const { KinesisClient, AddTagsToStreamCommand } = require("@aws-sdk/client-kinesis");
exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

If I am using the following it is giving me errors-

//ES6+ example 
import { KinesisClient, AddTagsToStreamCommand } from "@aws-sdk/client-kinesis";
     
exports.handler = async (event) => {
    // TODO implement
    const response = {
       statusCode: 200,
       body: JSON.stringify('Hello from Lambda!'),
    };
    return response; 
};
     
"Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module",

Question -

  1. How to make this work from the AWS lambda console ?
  2. Is there any harm in using as the ES5 vs ES6 ? is it only syntax or there are performance issues also?

Thanks !


Solution

    1. In order to fix the error, you could opt to use at least NodeJS version 18 or the recommended version NodeJS 20 as your Lambda function runtime and add "type": "module" to your package.json file. This will inform the Node runtime to use ES6 modules instead of the traditional ES5/CommonJS syntax.

    2. or consider changing the extension of your files to .mjs to force the NodeJS runtime to treat your file as an ES6 module.

    3. If you are using esbuild, you will have to make sure that your build output is compatible with the ES6 modules (import/export).

    4. If you were using TypeScript, configure your transpiler to produce a build output that is compatible with ES modules.

    5. If there is a performance issue, it would be minimal that we don't have to worry about it! PS: I recommend to test the compatibility of the ES5/CJS/CommonJS modules that the lambda uses when you change the runtime.