Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To incorporate ES modules in AWS Lambda that was generated by Amplify CLI, follow these steps:

  1. Install the "esm" package using npm or yarn:

    npm install esm
    # or
    yarn add esm
    
  2. Create a file named esm-wrapper.js in the root of your Amplify Lambda function.

  3. In the esm-wrapper.js file, add the following code:

    require = require("esm")(module);
    module.exports = require("./app");
    

    This code sets up the ESM loader and exports your actual Lambda function code from the app.js file.

  4. Update the amplify/backend/function/<function-name>/build.sh file to include the esm-wrapper.js file.

    # Before:
    cp -R ${functionDir} ${buildDir}/
    
    # After:
    cp -R ${functionDir}/* ${buildDir}/
    cp ${functionDir}/esm-wrapper.js ${buildDir}/index.js
    

    This code replaces the generated index.js file with the esm-wrapper.js file, which will be used to load your Lambda function.

  5. Update your Lambda function code in the app.js file to use ES modules syntax.

  6. Deploy your Lambda function with the Amplify CLI:

    amplify push function
    

That's it! Your Lambda function should now be using ESM syntax and the esm package.