Skip to content

When using esbuild plugin, import-is-undefined warning raised #471

@Karibash

Description

@Karibash

Environment

"@sentry/serverless": "7.99.0",
"@sentry/esbuild-plugin": "2.10.3",
"esbuild": "0.19.12",

Steps to Reproduce

If the file that is the entry point does not have a default export, an import-is-undefined warning will be raised at build time.

Cause of the issue

When injecting the stubs, the original module defaults are exported, which is the cause of this issue.

import * as OriginalModule from ${JSON.stringify(originalPath)};
export default OriginalModule.default;

Proposed amendment

I think it needs to be determined if the module has a default export.
There are two possible ways to do that.

Use dynamic import

It is possible to determine if a module has a default export by defining a function like the following.
However, there is a problem with this: it may affect the build if the module has side effects.

const moduleHasDefaultExport = async (path: string): Promise<boolean> => {
  const module = await import(path);
  return !!module.default;
};

Use AST parser

By using the AST parser as shown below, it is possible to determine if a module has a default export.
However, it seems excessive to introduce an AST parser just to solve this issue.

// I have no experience with the AST parser, so I am not sure if this code will work.
const moduleHasDefaultExport = async (path: string): Promise<boolean> => {
  const traverse = (node: Node): boolean => {
    if (node.type === 'ExportDefaultDeclaration') {
      return true;
    }

    if ('body' in node && Array.isArray(node.body)) {
      for (const childNode of node.body) {
        const result = traverse(childNode);
        if (result) {
          return true;
        }
      }
    }

    return false;
  };

  const script = await swc.parseFile(path);
  return traverse(script);
};

Metadata

Metadata

Assignees

No one assigned

    Projects

    Status

    No status

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions