Skip to content

Commit

Permalink
feat(lambda-nodejs): support esbuild inject (#19221)
Browse files Browse the repository at this point in the history
Closes #19133


----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
  • Loading branch information
jogold committed Mar 4, 2022
1 parent 5dc61ea commit 3432c45
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/@aws-cdk/aws-lambda-nodejs/README.md
Expand Up @@ -198,6 +198,7 @@ new lambda.NodejsFunction(this, 'my-handler', {
charset: lambda.Charset.UTF8, // do not escape non-ASCII characters, defaults to Charset.ASCII
format: lambda.OutputFormat.ESM, // ECMAScript module output format, defaults to OutputFormat.CJS (OutputFormat.ESM requires Node.js 14.x)
mainFields: ['module', 'main'], // prefer ECMAScript versions of dependencies
inject: ['./my-shim.js', './other-shim.js'] // allows to automatically replace a global variable with an import from another file
},
});
```
Expand Down
1 change: 1 addition & 0 deletions packages/@aws-cdk/aws-lambda-nodejs/lib/bundling.ts
Expand Up @@ -198,6 +198,7 @@ export class Bundling implements cdk.BundlingOptions {
...this.props.footer ? [`--footer:js=${JSON.stringify(this.props.footer)}`] : [],
...this.props.charset ? [`--charset=${this.props.charset}`] : [],
...this.props.mainFields ? [`--main-fields=${this.props.mainFields.join(',')}`] : [],
...this.props.inject ? this.props.inject.map(i => `--inject:${i}`) : [],
];

let depsCommand = '';
Expand Down
9 changes: 9 additions & 0 deletions packages/@aws-cdk/aws-lambda-nodejs/lib/types.ts
Expand Up @@ -279,6 +279,15 @@ export interface BundlingOptions {
* @default ['main', 'module']
*/
readonly mainFields?: string[];

/**
* This option allows you to automatically replace a global variable with an
* import from another file.
*
* @see https://esbuild.github.io/api/#inject
* @default - no code is injected
*/
readonly inject?: string[]
}

/**
Expand Down
3 changes: 2 additions & 1 deletion packages/@aws-cdk/aws-lambda-nodejs/test/bundling.test.ts
Expand Up @@ -208,6 +208,7 @@ test('esbuild bundling with esbuild options', () => {
'process.env.STRING': JSON.stringify('this is a "test"'),
},
format: OutputFormat.ESM,
inject: ['./my-shim.js'],
});

// Correctly bundles with esbuild
Expand All @@ -224,7 +225,7 @@ test('esbuild bundling with esbuild options', () => {
defineInstructions,
'--log-level=silent --keep-names --tsconfig=/asset-input/lib/custom-tsconfig.ts',
'--metafile=/asset-output/index.meta.json --banner:js="/* comments */" --footer:js="/* comments */"',
'--charset=utf8 --main-fields=module,main',
'--charset=utf8 --main-fields=module,main --inject:./my-shim.js',
].join(' '),
],
}),
Expand Down

0 comments on commit 3432c45

Please sign in to comment.