Reputation: 2966
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:
// @ts-ignore
before the actual import will silent this errorNow, 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
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