Bakir Jusufbegovic
Bakir Jusufbegovic

Reputation: 2966

AWS Lambda Layers - Typescript - Problem with specifying imports in index handler since, in the layer, then need to be in form /opt/nodejs/

I'm using Typescript to write AWS Lambda code (both handlers and shared code) and then I transpile the code, add node_modules to the dir where transpiled code exist and publish the Lambda. This works correctly.

Now, if I want to add shared code as part of AWS Lambda layer, this is where it gets tricky with Typescript. Consider following code structure that I have:

.
├── index.ts
├── lib
│   └── userData.ts
├── node_modules
├── package-lock.json
├── package.json
└── tsconfig.json

I would like to have a layer which contains:

node_modules
userData.ts

I'm aware of the structure that needs to exist when publishing the layer and also how to reference it in the index.ts (handler method) code.

Before layers, my index.ts code looks like this:

import { UserData } from "./lib/userData";

export const handler = async (event: any = {}): Promise<any> => {
   # some code here
}

Because I want to import UserData from the layer, import would need to look like this:

import { UserData } from "./opt/nodejs/userData";

However, if I specify this, and try to transpile code (before creating a aws lambda package), I will get an obvious error:

index.ts:1:26 - error TS2307: Cannot find module '/opt/nodejs/userData' or its corresponding type declarations.

1 import { UserData } from "/opt/nodejs/userData";
                           ~~~~~~~~~~~~~~~~~~~~~~

There are some ways to avoid this:

  1. Adding // @ts-ignore before the actual import will silent this error
  2. Dirty/hacky way would be to edit this import on transpiled code which is not what I want to do.

Now, this seems like a chicken and egg problem and I'm new to the AWS Lambdas, so any advice on how to handle this situation without these hacky ways to avoid it?

Upvotes: 7

Views: 2722

Answers (1)

Victor Peralta
Victor Peralta

Reputation: 99

I solved this using typescript path mappings. You can add this to your tsconfig.json.

"baseUrl": ".",
"paths": {
  "/opt/nodejs/*": ["src/testLayer/nodejs/*"]

This specifies to the TS compiler that the /opt/nodejs/ path is really pointing to src/testLayer/nodejs/ in our local directory structure, so it gets the files from there

Upvotes: 4

Related Questions