Skip to content

Bug: ESM Require not supported use import with suggested banner. #2523

Closed
@Xenoha

Description

@Xenoha

Expected Behavior

I would expect powertools to be able to compile to ESM with included banner.

Current Behavior

{
"errorType": "ReferenceError",
"errorMessage": "require is not defined in ES module scope, you can use import instead",
"stack": [
"ReferenceError: require is not defined in ES module scope, you can use import instead",
" at ProviderService.captureHTTPsGlobal (file:///opt/nodejs/node_modules/@aws-lambda-powertools/tracer/lib/esm/provider/ProviderService.js:25:9)",
" at new Tracer (file:///opt/nodejs/node_modules/@aws-lambda-powertools/tracer/lib/esm/Tracer.js:122:27)",
" at (/infra/src/pipeline/config/lambda-fns/common/powertools.ts:24:16)",
" at ModuleJob.run (node:internal/modules/esm/module_job:222:25)",
" at async ModuleLoader.import (node:internal/modules/esm/loader:323:24)",
" at async _tryAwaitImport (file:///var/runtime/index.mjs:1008:16)",
" at async _tryRequire (file:///var/runtime/index.mjs:1057:86)",
" at async _loadUserApp (file:///var/runtime/index.mjs:1081:16)",
" at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)",
" at async start (file:///var/runtime/index.mjs:1282:23)"
]
}

Code snippet

		const powerToolsLayer = LayerVersion.fromLayerVersionArn(scope, `${id}-powertools-layer`, `arn:aws:lambda:${Stack.of(scope).region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:2`)

		super(scope, id, {
			...rest,
			handler: 'handler',
			runtime: Runtime.NODEJS_20_X,
			tracing: Tracing.ACTIVE,
			architecture: Architecture.ARM_64,
			timeout: Duration.seconds(30),
			layers: rest.layers ? [...rest.layers, powerToolsLayer] : [powerToolsLayer],
			environment: {
				NODE_OPTIONS: '--enable-source-maps',
				...props.environment,
			},
			logGroup: new LogGroup(scope, `${id}-log-group`, {
				logGroupName: `/aws/lambda/${id}`,
				retention: getRetention(stage),
				removalPolicy: stage === 'Prod' ? RemovalPolicy.RETAIN : RemovalPolicy.DESTROY,
			}),
			bundling: {
				minify: true,
				sourceMap: true,
				keepNames: true,
				sourcesContent: true,
				format: OutputFormat.ESM,
				mainFields: ['module', 'main'],
				esbuildArgs: { '--tree-shaking': 'true' },
				banner: "import { createRequire } from 'module';const require = createRequire(import.meta.url);",
				externalModules: ['@aws-sdk/*', '@aws-lambda-powertools/*'],
			},
		})

Steps to Reproduce

Lambda..

import { captureLambdaHandler } from '@aws-lambda-powertools/tracer/middleware'
import { injectLambdaContext } from '@aws-lambda-powertools/logger/middleware'
import { logMetrics } from '@aws-lambda-powertools/metrics/middleware'
import { logger, metrics, tracer } from './common/powertools'

import { PipelineEvent } from '../../../../../types'

const { SLACK_CHANNEL = '' } = process.env

const lambdaHandler = async (event: PipelineEvent) => {
	await sendToSlack(event)
}

const handler = middy(lambdaHandler)
	.use(captureLambdaHandler(tracer))
	.use(logMetrics(metrics, { captureColdStartMetric: true }))
	.use(injectLambdaContext(logger, { clearState: true }))

export { handler }```


### Possible Solution

any work being done on ESM bundling, or should we just switch to CJS?

### Powertools for AWS Lambda (TypeScript) version

latest

### AWS Lambda function runtime

20.x

### Packaging format used

Lambda Layers

### Execution logs

```Shell
{
    "errorType": "ReferenceError",
    "errorMessage": "require is not defined in ES module scope, you can use import instead",
    "stack": [
        "ReferenceError: require is not defined in ES module scope, you can use import instead",
        "    at ProviderService.captureHTTPsGlobal (file:///opt/nodejs/node_modules/@aws-lambda-powertools/tracer/lib/esm/provider/ProviderService.js:25:9)",
        "    at new Tracer (file:///opt/nodejs/node_modules/@aws-lambda-powertools/tracer/lib/esm/Tracer.js:122:27)",
        "    at <anonymous> (/infra/src/pipeline/config/lambda-fns/common/powertools.ts:24:16)",
        "    at ModuleJob.run (node:internal/modules/esm/module_job:222:25)",
        "    at async ModuleLoader.import (node:internal/modules/esm/loader:323:24)",
        "    at async _tryAwaitImport (file:///var/runtime/index.mjs:1008:16)",
        "    at async _tryRequire (file:///var/runtime/index.mjs:1057:86)",
        "    at async _loadUserApp (file:///var/runtime/index.mjs:1081:16)",
        "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)",
        "    at async start (file:///var/runtime/index.mjs:1282:23)"
    ]
}

Metadata

Metadata

Assignees

Labels

not-a-bugNew and existing bug reports incorrectly submitted as bugrejectedThis is something we will not be working on. At least, not in the measurable futuretracerThis item relates to the Tracer Utility

Type

No type

Projects

Status

Closed

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions