Skip to content

Conversation

@stevezhu
Copy link

@stevezhu stevezhu commented Sep 10, 2025

Description

The static import regex is missing an exclusion for the case where the import statement is a comment. The esm shim will be added below the comment instead of the actual last import statement in this case. I didn't spend much time on the regex edit, so if there's a better implementation, please make any suggestions for improvements!

Changed the regex to ensure start of line(?<=^(|\s|;)). Not sure if this is valid for all cases. For example, an invalid case where you have a space before the semicolon:

// whitespace at start of line
 ;import __cjs_url__ from 'node:url';

An alternative is using a negative lookbehind for // ((?<!\/\/.*?)) which can be seen in the first commit:

const ESMStaticImportRe =
-  /(?<=\s|^|;)import\s*([\s"']*(?<imports>[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu
const ESMStaticImportRe =
+  /(?<!\/\/.*?)(?<=\s|^|;)import\s*([\s"']*(?<imports>[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu

Additional context

I ran into this issue where it added the esm shim under the comment below instead. I didn't test thoroughly but it seems like the esm shim plugin runs before comments are removed in the build process.

Example:

// import { $ZodType } from "./schemas.js";
// esm shim would be added here
const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => {
    var _a;
    inst._zod ?? (inst._zod = {});
    inst._zod.def = def;
    (_a = inst._zod).onattach ?? (_a.onattach = []);
});

What is the purpose of this pull request?

  • Bug fix
  • New Feature
  • Documentation update
  • Other

Before submitting the PR, please make sure you do the following

@stevezhu stevezhu changed the title Add negative lookbehind for comment in static import regex fix: add negative lookbehind for comment in static import regex Sep 10, 2025
@stevezhu stevezhu changed the title fix: add negative lookbehind for comment in static import regex fix(build): add negative lookbehind for comment in static import regex Sep 10, 2025
@stevezhu stevezhu changed the title fix(build): add negative lookbehind for comment in static import regex fix: add negative lookbehind for comment in static import regex Sep 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant