Search code examples
amazon-web-servicesaws-lambdaaws-cdkesbuildesbuild-plugin

Esbuild plugins in AWS CDK Lambda?


The issue:

  • Esbuild allows using plugins during build step via a special config's property: #1
  • At the same time there's an option to configure esbuild options in AWS CDK: #2
  • But the type of esbuild configuration in AWS CDK does not include an explicit option to allow plugins: #3
  • It allows an option to set any other CLI flags with the esbuildArgs property, though: #4
  • But it looks like esbuild would not allow plugin configuration via the CLI flags.

Is there a way to circumvent this somehow?

P. S. Although it makes the question less generic, but to add more context: I was thinking if it's possible to replace import.meta.dirname tokens with the actual string values on the build step, because these guys become completely useless once all the files are being merged into one (to run within Lambda).


Solution

  • The problem is that esbuild plugins are only available on the asynchronous API, but the AWS CDK does not support async operations. It's the same reason why plugins are not available on the esbuild CLI.

    Unfortunately there is no nice way around this. A workaround is to create a esbuild build script (which can call the async API) and spawn this script as a child process with something like child_process.spawnSync('node', ['build.js']); In order to integrate nicely with the AWS CDK, you'll also have to implement the ILocalBundling interface.

    Third-party packages can make this slightly easier, or at least provide a blueprint for your custom code. Here's a complete example that's using the package @mrgrain/cdk-esbuild (which I maintain). But you don't need to use a third-party package, you can easily build this yourself.

    There has also been a proposal to make external build scripts easier to use, but as of writing this answer, it is not yet available.


    Disclosure:

    I used to work on the AWS CDK team.
    I am the maintainer of @mrgrain/cdk-esbuild