Skip to content

Bug: ReferenceError: require is not defined in ES module scope when using @aws-lambda-powertools/tracer in ES Module #2605

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
william-mens opened this issue Jun 5, 2024 · 4 comments
Assignees
Labels
bug-upstream This item is related to a bug caused by upstream dependency tracer This item relates to the Tracer Utility

Comments

@william-mens
Copy link

Expected Behavior

The package should work seamlessly with ES module syntax without throwing a require error.

Current Behavior

I'm encountering an issue when trying to use the @aws-lambda-powertools/tracer package in a TypeScript project configured as an ES module. The error message suggests that there is an internal use of require which is not supported in ES module scope.

Code snippet

//route.ts file

import { APIGatewayProxyResult, Context } from 'aws-lambda';
import { Tracer } from '@aws-lambda-powertools/tracer';
import { AccountController } from './controllers/AccountController.js';
import { loadConfig } from './config.js';

const tracer = new Tracer({ serviceName: 'transflowAccountService' });

export const updateAccountHandler = async (event: any, context: Context): Promise => {
tracer.getSegment();

const container = await loadConfig();
const account = new AccountController(container);
const response = await account.suspend(event.body as any);
return response;

};

Steps to Reproduce

  1. Configure package.json with "type": "module".
  2. Install @aws-lambda-powertools/tracer and use it in a TypeScript file with ES module syntax.
  3. tsConfig.json
    {
    "compilerOptions": {
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "declaration": true,
    "declarationMap": true,
    "forceConsistentCasingInFileNames": true,
    "noEmitOnError": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "removeComments": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "resolveJsonModule": true,
    "pretty": true,
    "sourceMap": true,
    "strict": true,
    "module": "esnext",
    "moduleResolution": "node",
    "target": "es2019",
    "outDir": "build",
    "rootDir": "src",
    "lib": ["es2019", "DOM"]
    },
    "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node",
    },
    "exclude": ["node_modules", "built"],
    // "include": ["src/.ts", "src/**/.ts"]
    "include": ["src/**/*"],
    }

Possible Solution

No response

Powertools for AWS Lambda (TypeScript) version

latest

AWS Lambda function runtime

20.x

Packaging format used

npm

Execution logs

2024-06-05T09:08:00.072Z undefined ERROR Uncaught Exception 
{
    "errorType": "ReferenceError",
    "errorMessage": "require is not defined in ES module scope, you can use import instead\nThis file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains \"type\": \"module\". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.",
    "stack": [
        "ReferenceError: require is not defined in ES module scope, you can use import instead",
        "This file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains \"type\": \"module\". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.",
        "    at ProviderService.captureHTTPsGlobal (file:///var/task/node_modules/@aws-lambda-powertools/tracer/lib/esm/provider/ProviderService.js:33:9)",
        "    at new Tracer (file:///var/task/node_modules/@aws-lambda-powertools/tracer/lib/esm/Tracer.js:122:27)",
        "    at file:///var/task/build/routes.js:11:16",
        "    at ModuleJob.run (node:internal/modules/esm/module_job:222:25)",
        "    at async ModuleLoader.import (node:internal/modules/esm/loader:316:24)",
        "    at async _tryAwaitImport (file:///var/runtime/index.mjs:1008:16)",
        "    at async _tryRequire (file:///var/runtime/index.mjs:1057:37)",
        "    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)"
    ]
}
@william-mens william-mens added bug Something isn't working triage This item has not been triaged by a maintainer, please wait labels Jun 5, 2024
Copy link

boring-cyborg bot commented Jun 5, 2024

Thanks for opening your first issue here! We'll come back to you as soon as we can.
In the meantime, check out the #typescript channel on our Powertools for AWS Lambda Discord: Invite link

@dreamorosi
Copy link
Contributor

Hi, thank you for opening this issue.

This is a known limitation of the AWS X-Ray SDK for Node.js that doesn't support ESM.

If you want to use ESM you need to provide a polyfill for the require keyword during your bundling process, you can find a reference on how to do this in our docs here.

Duplicate of #2555, #2523, #2464

@dreamorosi dreamorosi added tracer This item relates to the Tracer Utility bug-upstream This item is related to a bug caused by upstream dependency need-response This item requires a response from a customer and will considered stale after 2 weeks and removed bug Something isn't working triage This item has not been triaged by a maintainer, please wait labels Jun 5, 2024
@dreamorosi dreamorosi moved this from Triage to Pending review in Powertools for AWS Lambda (TypeScript) Jun 5, 2024
@dreamorosi dreamorosi self-assigned this Jun 5, 2024
@william-mens
Copy link
Author

@dreamorosi, thank you for your response. I've noted it and will make the necessary updates. This is very helpful.

@github-project-automation github-project-automation bot moved this from Pending review to Coming soon in Powertools for AWS Lambda (TypeScript) Jun 5, 2024
Copy link
Contributor

github-actions bot commented Jun 5, 2024

⚠️ COMMENT VISIBILITY WARNING ⚠️

This issue is now closed. Please be mindful that future comments are hard for our team to see.

If you need more assistance, please either tag a team member or open a new issue that references this one.

If you wish to keep having a conversation with other community members under this issue feel free to do so.

@dreamorosi dreamorosi moved this from Coming soon to Closed in Powertools for AWS Lambda (TypeScript) Jun 7, 2024
@dreamorosi dreamorosi removed the need-response This item requires a response from a customer and will considered stale after 2 weeks label Jun 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug-upstream This item is related to a bug caused by upstream dependency tracer This item relates to the Tracer Utility
Projects
Development

No branches or pull requests

2 participants