Utilizing AWS CDK with Node.jsFunction to import a module that is exported as "export="

Is it possible to utilize modules (such as sharp) that are exported as export = someModule in a Lambda function defined with the NodejsFunction from the aws-cdk-lib?
It seems like the require statement (const xxx = require('module')) does not work with the TypeScript code for Lambdas that is bundled by CDK.

Both of the attempted import methods resulted in an error.

import sharp from 'sharp'
import * as sharp from 'sharp'
import sharp = require('sharp')
An error occurred while installing the "sharp" module
Unable to locate module '../build/Release/sharp-linux-x64.node'
Require stack:
- /var/task/index.js
- /var/runtime/index.mjs

The Lambda function is defined in the CDK code as shown below.

import { aws_lambda_nodejs as lambda } from 'aws-cdk-lib'

const fn = new lambda.NodejsFunction(scope, 'fn-id', {
  entry: 'lib/lambda/my-fn.ts',
  functionName: 'fn-name'
})

Answer №1

When setting up your NodejsFunction in the CDK Stack, make sure to include node_modules or external modules if needed.

To explore different bundling options, refer to the documentation.

Below is a sample code snippet showcasing the usage of externalModules, nodeModules, and layers for resource access:

this.exampleLambdaFunction = new NodejsFunction(this, `exampleLambdaFunction`, {
  runtime: Runtime.NODEJS_18_X,
  handler: "handler",
  bundling: { minify: false, nodeModules: ["@aws-sdk/client-sfn", "axios", "axios-retry"], externalModules: ["aws-sdk", "crypto-js"] },
  layers: [lambdaLayerStack.getSecrets, lambdaLayerStack.generateMagentoAuthorisationHeader]
});

Answer №2

When working on M1 architecture, it is essential to properly install the sharp package in order to avoid errors during lambda execution.

npm install --platform=linux --arch=x64 sharp

If not installed correctly, you might encounter an error message like:

Could not load the \"sharp\" module using the linux-x64 runtime\

To import sharp after installation, use the following syntax:

import sharp from 'sharp' // for TypeScript

const sharp = require("sharp") // for JavaScript

If the error persists during cdk deploy, you can resolve it by configuring sharp as a separate module that needs to be installed rather than bundled. Add the following option to your NodejsFunction:

const fn = new lambda.NodejsFunction(scope, 'fn-id', {
  entry: 'lib/lambda/my-fn.ts',
  functionName: 'fn-name',
  bundling: {
    nodeModules: ['sharp'],
  }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered while loading a plugin in Typescript and RequireJS compilation process

Currently, I am working on a Typescript application in Visual Studio 2015 where RequireJS is used for loading modules. I have successfully loaded various modules from .ts classes and external libraries by using their typing .d.ts files. However, I have en ...

Transform Promise<any> into a designated type failure

Beginner inquiry concerning typescript/angular4+/ionic4. I have a service set up to make backend REST calls, and based on the response received, I need to store that data in local storage for future reference. However, I am encountering a type conversion e ...

Guide on assigning JSON response values to TypeScript variables in Angular 4

I'm just starting with Angular 4 and I'm attempting to retrieve a JSON value using http.post. The response I'm receiving is: {"status":"SUCCESS"} component onSubmit(value: any) { console.log("POST"); let url = `${this.posts_Url}`; t ...

Angular 4 Filtering Pipe: Simplify Data Filtering in Angular

Attempting to replicate AngularJS's OrderBy feature. Working with an array like this, I am aiming to filter the cars by their car category. [ { "car_category": 3, "name": "Fusion", "year": "2010" }, { "car_category": 2, "na ...

Is there an improved method for designing a schema?

Having 4 schemas in this example, namely Picture, Video, and Game, where each can have multiple Download instances. While this setup works well when searching downloads from the invoker side (Picture, Video, and Game), it becomes messy with multiple tables ...

Traversing an array in JavaScript to create a new array

I have a function that returns an array based on a condition. Here is the code snippet: const operationPerResource = (resource: ResourceTypes): OperationTypes[] => { const operations = cases[resource] || cases.default; return operations; }; Now, I ...

Property ngIf in Angular is not being supplied by any relevant directive within the embedded template

When attempting to use ngIf, I encountered an error with a red underline. The error message states: "Property ngIf is not provided by any applicable directive on an embedded template." I then attempted to import commonModel, but received a new error: "src ...

Can a type be referenced using the generic name?

My selection includes: export type DocumentType = | Item | List | User export type DocumentInputType = | ItemInputType | ListInputType | UserInputType I want to develop a feature that can determine the input type based on the document type wi ...

Automating a login prompt with dual inputs using WebdriverIO: A step-by-step guide

I'm having trouble automating the login prompt as shown in the attached image. I've attempted to fill in both fields using WebdriverIO but so far have been unsuccessful. I explored using alert methods like browser.sendAlertText(), but none of the ...

Displaying Modal from a separate component

CardComponent: export class Card extends Component<Prop, State> { state = { isCancelModalOpen: false, }; marketService = new MarketService(); deleteMarket = () => { this.marketService .deleteMar( ...

Angular 6 is experiencing an issue with the functionality of the file toggle JS

Currently, I am utilizing the file toggle.js within the Urban theme. In the HTML chatbox, using the img, the file toggle.js is hardcoded and is functioning properly. However, when implementing code in Angular 6, the toggle.js is not functioning as expecte ...

NestJS is having trouble importing generated types from the Prisma client

When working with Prisma in conjunction with NestJs, I encountered an issue after defining my model and generating it using npx prisma generate. Upon importing the generated type, I can easily infer its structure: import { FulfilmentReport, FulfilmentRepor ...

Unlocking Global Opportunities with Stencil for Internationalization

Hi there, I've been attempting to implement Internationalization in my stencil project but unfortunately, it's not working as expected. I'm not sure what's causing the issue, and all I'm seeing is a 404 error. I followed these arti ...

Display a separate component within a primary component upon clicking a button

Looking to display data from a placeholder module upon component click. As a beginner with React, my attempts have been unsuccessful so far. I have a component that lists some information for each element in the module as a list, and I would like to be ab ...

Several cucumber reports are showing an error message containing special characters

I am encountering an issue in the multiple cucumber report where error messages are being displayed with special characters. Is there a way to format them properly? I am currently learning Playwright, Typescript, and CucumberJs and generating reports for m ...

Can :[Interface] be considered a correct array declaration in Typescript?

My TypeScript codebase is filled with code snippets like the one below... export interface SomeType { name: string; } export interface SomeComposedType { things: [SomeType]; } Everything was working smoothly until I started experiencing issues su ...

Tips for determining if an HTMLElement has already been created

One issue I'm facing is with a third party component that emits an "onCellEdit" event and passes a cell element as a parameter. My goal is to automatically select the entire text in the input element generated inside this cell when the event occurs. ...

Transmitting form data inputted by the user to a modal that resides in the same component, all without the need for child or parent components or

In need of a solution where users can input answers to questions and have all the entered data displayed in a popup alongside the respective question. If a user chooses not to answer a question, I do not want that question or any related information to be ...

Difficulty persisting when removing accents/diacritics from a string in Angular with IE 11

When attempting to utilize the String.normalize("NFD").replace(/[\u0300-\u036f]/g, "") method, I encountered an issue in IE11. ERROR TypeError: The object does not support the property or method "normalize" ...

`Filter an array retrieved from the backend in a TypeScript environment`

I have asked other questions in the past, but I received unhelpful answers. I am still looking for proper solutions. Currently, I am retrieving an array from the backend using Redux. const { movies, message } = useAppSelector(state => state.movies); ...