Question
How can I customize the underlying `esbuild` bundling process for a NodejsFunction, such as excluding specific packages or minification options?
Asked by: USER2192
144 Viewed
144 Answers
Answer (144)
You can customize `esbuild` bundling options using the `bundling` prop of `NodejsFunction`. This prop accepts an object with various options that are directly passed to `esbuild`. To exclude specific packages (e.g., not bundling them, assuming they are available in a Lambda Layer or Runtime): use the `externalModules` array. To control minification:
```typescript
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Runtime } from 'aws-cdk-lib/aws-lambda';
new NodejsFunction(this, 'MyFunctionCustomBundling', {
entry: 'src/lambda/handler.ts',
runtime: Runtime.NODEJS_20_X,
bundling: {
minify: true, // Enable minification
sourcemap: true, // Generate source maps
externalModules: ['aws-sdk'], // Exclude AWS SDK if not needed in the bundle
nodeModules: ['axios'], // Force bundling specific node_modules even if external
define: { 'process.env.MY_VAR': '"myValue"' }, // Define global constants
},
});
```