Search code examples
node.jsaws-cdktsctypescript-decoratoresbuild

How to enable decorators in NodeJs lambda function that are built and deployed using AWS CDK?


I have refactored my lambda function by applying DI principles using the tsyringe library. Unfortunately, after my lamdas are built to the cloud, services have not been injected properly and dependencies are undefined. The issue is probably connected to esBuild because I could replicate this issue locally if I used it for code compilation. If I compile this code locally using TSC this issue does not occur and dependencies are properly injected. How can I tinker the build process so I can still use AWS CDK and dependencies will be injected?


Solution

  • It looks like tsyringe requires the emitDecoratorMetadata option, which isn't supported natively by esbuild.

    You have a couple of options to make it work:

    1. Set the preCompilation option to true. This will run your build with tsc instead of esbuild. It'll be a bit slower, but you'll be able to emit the decorators.
    2. Use a plugin like esbuild-plugin-tsc.

    For Lambda, option #1 here is probably fine.