Skip to content

Not possible to debug CDK ES module project that uses import.meta #44

@kristiandreher

Description

@kristiandreher

Thanks for a really cool project!

However when trying to debug a CDK ES module project that uses import.meta to resolve dirname lld throws an error.

▲ [WARNING] "import.meta" is not available with the "cjs" output format and will be empty [empty-import-meta]

    lib/esm-test-app-stack.ts:8:49:
      8 │ const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
        ╵                                                  ~~~~~~~~~~~

  You need to set the output format to "esm" for "import.meta" to work correctly.

Error: Error running CDK code in worker: Invalid URL

lib/esm-test-app-stack:

import { Duration, Stack, type StackProps } from "aws-cdk-lib";
import { Construct } from "constructs";
import * as url from "url";
import { resolve } from "path";
import { NodejsFunction, OutputFormat } from "aws-cdk-lib/aws-lambda-nodejs";
import { Runtime } from "aws-cdk-lib/aws-lambda";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

export class EsmTestAppStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    new NodejsFunction(this, "Lambda", {
      timeout: Duration.seconds(20),
      memorySize: 1024,
      runtime: Runtime.NODEJS_20_X,
      entry: resolve(__dirname, "./handler.ts"),
      environment: {
        NODE_OPTIONS: "--enable-source-maps",
        LOG_LEVEL: "DEBUG",
      },
      bundling: {
        minify: true,
        sourceMap: true,
        externalModules: [],
        platform: "node",
        // ESM important properties:
        mainFields: ["module", "main"],
        format: OutputFormat.ESM,
        banner:
          "const require = (await import('node:module')).createRequire(import.meta.url);",
      },
    });
  }
}

Metadata

Metadata

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions