Skip to content
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

[@rollup/plugin-esm-shim] Shim inserted incorrectly if source file has import in comment #1709

Open
EvanHahn opened this issue Apr 18, 2024 · 0 comments

Comments

@EvanHahn
Copy link

Expected Behavior

The shim should be inserted in the right place, even if the source file contains static imports in comments.

For example, the shim should be inserted right after the import in the file below:

import foo from "./other_module.js";

// Triggers the shim
require();

/*
import BAD from "./bad";
*/

Actual Behavior

The shim is inserted in a strange place, causing syntax errors.

Additional Information

I believe this bug happens because the plugin tries to insert the shim after the last import, but incorrectly detects them when they're inside comments.

imports are detected with the following regular expression:

export const ESMStaticImportRegex =
/(?<=\s|^|;)import\s*([\s"']*(?<imports>[\w\t\n\r $*,/{}]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"\n]*[^\s"](?=\s*")|(?<='\s*)[^'\n]*[^\s'](?=\s*'))\s*["'][\s;]*/gm;

This expression is unaware of comments.

I would probably solve this by parsing the AST rather than using a regular expression. Let me know if you'd like me to make that pull request.

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

No branches or pull requests

1 participant