0

Is there any way to use modules (e.g. sharp) exported as export = someModule in a Lambda function defined using NodejsFunction in the aws-cdk-lib?
The require statement(const xxx = require('module')) does not seem to work with the Lambda TypeScript code that CDK bundles.

Both of the following import writing methods resulted in the error.

import sharp from 'sharp'
import * as sharp from 'sharp'
import sharp = require('sharp')
Something went wrong installing the \"sharp\" module
Cannot find module '../build/Release/sharp-linux-x64.node'
Require stack:
- /var/task/index.js
- /var/runtime/index.mjs

The CDK code defines the Lambda function as follows.

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'
})
kusumoto_teruya
  • 2,415
  • 4
  • 23
  • 38
  • Is the error thrown at synth-time, deploy-time or run-time? – fedonev Dec 15 '22 at 08:39
  • Run-time. No deploy errors. – kusumoto_teruya Dec 15 '22 at 08:55
  • I suspect this is a sharp-specific problem. Is CDK using [esbuild](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs-readme.html#local-bundling) or Docker for bundling? See the [sharp installation docs](https://sharp.pixelplumbing.com/install#esbuild). – fedonev Dec 15 '22 at 10:27

1 Answers1

0

If you're introducing node_modules or external modules for your NodejsFunction, you'll need to specify this in your CDK Stack.

Look at bundling options to learn more.

Here's an example that uses externalModules, nodeModules and layers to access resources.

this.lambdaFunctionExample= new NodejsFunction(this, `lambdaFunctionExample`, {
  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]
});
Lloukas
  • 89
  • 7