skip to Main Content

I’m attempting to deploy a lambda implemented in typescript via CDK.

I am able to deploy the lambda successfully, but when I test it, I get the following error:

{
  "errorType": "Runtime.ImportModuleError",
  "errorMessage": "Error: Cannot find module 'index'nRequire stack:n- /var/runtime/index.mjs",
  "trace": [
    "Runtime.ImportModuleError: Error: Cannot find module 'index'",
    "Require stack:",
    "- /var/runtime/index.mjs",
    "    at _loadUserApp (file:///var/runtime/index.mjs:996:17)",
    "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1031:21)",
    "    at async start (file:///var/runtime/index.mjs:1194:23)",
    "    at async file:///var/runtime/index.mjs:1200:1"
  ]
}

The lambda is declared in CDK like so:

    const postImages = new lambda.Function(scope, utils.prefixed('post_images'), {
        runtime: lambda.Runtime.NODEJS_18_X,
        handler: 'index.lambdaHandler',
        code: lambda.Code.fromAsset('./sd_service/post_images')
    })

The contents of ./sd_service/post_images looks like this:

enter image description here

index.ts:

import { Context, APIGatewayEvent, APIGatewayProxyResult } from 'aws-lambda';

export const lambdaHandler = async (event: APIGatewayEvent, context: Context): Promise<APIGatewayProxyResult> => {
    console.log(`Event: ${JSON.stringify(event, null, 2)}`);
    console.log(`Context: ${JSON.stringify(context, null, 2)}`);
    return {
        statusCode: 200,
        body: JSON.stringify({
            message: 'hello world',
        }),
    };
};

tsconfig.json:


{
    "$schema": "https://json.schemastore.org/tsconfig",
    "display": "Node 18",

    "compilerOptions": {
        "lib": ["es2022"],
        "module": "commonjs",
        "target": "es2022",

        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "moduleResolution": "node"
    },
    "exclude": ["node_modules", "**/*.test.ts"]
}

package.json:

{
  "name": "post_images",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/aws-lambda": "^8.10.111",
    "@types/node": "^18.14.6",
    "aws-sdk": "^2.1330.0",
    "typescript": "^4.9.5"
  },
  "dependencies": {
    "aws-lambda": "^1.0.7"
  }
}

What have I done wrong, and how can I get the lambda to work?

2

Answers


  1. Check the file structure on the Lambda Console.

    Login or Signup to reply.
  2. Make sure you have index.ts at the root of your project after deploying. A common problem when deploying an archive: if you archive a folder with all the files, then in the root of the archive will be a folder with files, but there should be files (including the entry point).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search