Skip to content

Commit e894c7e

Browse files
dreamorosiam29d
andauthored
docs(tracer): add ESM instructions to tracer usage docs (#2630)
Co-authored-by: Alexander Schueren <[email protected]>
1 parent b2109af commit e894c7e

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

Diff for: docs/core/tracer.md

+66
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,72 @@ The `Tracer` utility must always be instantiated outside of the Lambda handler.
4242
--8<-- "examples/snippets/tracer/basicUsage.ts"
4343
```
4444

45+
#### Using with ESM?
46+
47+
Tracer relies on the AWS X-Ray SDK for Node.js, which is distributed as a CommonJS module and uses `require`.
48+
49+
To use it in an ESM project, you can instruct your bundler to use the `require` syntax for specific dependencies while using ESM for everything else. This is commonly known as [polyfill](https://developer.mozilla.org/en-US/docs/Glossary/Polyfill){target="_blank"}.
50+
51+
??? note "Code snippets for AWS CDK and AWS SAM CLI with `esbuild`"
52+
53+
=== "With AWS CDK"
54+
55+
```typescript hl_lines="15 20-21"
56+
import { Stack, type StackProps } from 'aws-cdk-lib';
57+
import { Construct } from 'constructs';
58+
import { NodejsFunction, OutputFormat } from 'aws-cdk-lib/aws-lambda-nodejs';
59+
import { Runtime } from 'aws-cdk-lib/aws-lambda';
60+
61+
export class MyStack extends Stack {
62+
public constructor(scope: Construct, id: string, props?: StackProps) {
63+
super(scope, id, props);
64+
65+
const handler = new NodejsFunction(this, 'helloWorldFunction', {
66+
runtime: Runtime.NODEJS_20_X,
67+
handler: 'handler',
68+
entry: 'src/index.ts',
69+
bundling: {
70+
format: OutputFormat.ESM,
71+
minify: true,
72+
esbuildArgs: {
73+
"--tree-shaking": "true",
74+
},
75+
banner:
76+
"import { createRequire } from 'module';const require = createRequire(import.meta.url);", // (1)!
77+
},
78+
});
79+
}
80+
}
81+
```
82+
83+
1. `esbuild` will include this arbitrary code at the top of your bundle to maximize CommonJS compatibility _(`require` keyword)_.
84+
85+
=== "With AWS SAM"
86+
87+
```yaml hl_lines="14 17-18"
88+
Transform: AWS::Serverless-2016-10-31
89+
Resources:
90+
HelloWorldFunction:
91+
Type: AWS::Serverless::Function
92+
Properties:
93+
Runtime: nodejs20.x
94+
Handler: src/index.handler
95+
Metadata:
96+
BuildMethod: esbuild
97+
BuildProperties:
98+
Minify: true
99+
Target: 'ES2020'
100+
Sourcemap: true
101+
Format: esm
102+
EntryPoints:
103+
- src/index.ts
104+
Banner:
105+
js: "import { createRequire } from 'module';const require = createRequire(import.meta.url);" # (1)!
106+
107+
```
108+
109+
1. `esbuild` will include this arbitrary code at the top of your bundle to maximize CommonJS compatibility _(`require` keyword)_.
110+
45111
### Utility settings
46112

47113
The library has three optional settings. You can set them as environment variables, or pass them in the constructor:

0 commit comments

Comments
 (0)