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

fix: strip comment for syntax detection #196

Merged
merged 4 commits into from
Jan 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions src/syntax.ts
Original file line number Diff line number Diff line change
@@ -7,16 +7,19 @@ import { isNodeBuiltin, getProtocol } from "./utils";
const ESM_RE =
/([\s;]|^)(import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;

const CJS_RE =
/([\s;]|^)(module.exports\b|exports\.\w|require\s*\(|global\.\w)/m;

const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;

const BUILTIN_EXTENSIONS = new Set([".mjs", ".cjs", ".node", ".wasm"]);

export function hasESMSyntax(code: string): boolean {
return ESM_RE.test(code);
return ESM_RE.test(code.replace(COMMENT_RE, ""));
}

const CJS_RE =
/([\s;]|^)(module.exports\b|exports\.\w|require\s*\(|global\.\w)/m;
export function hasCJSSyntax(code: string): boolean {
return CJS_RE.test(code);
return CJS_RE.test(code.replace(COMMENT_RE, ""));
}

export function detectSyntax(code: string) {
2 changes: 2 additions & 0 deletions test/syntax.test.ts
Original file line number Diff line number Diff line change
@@ -82,6 +82,8 @@ const staticTests = {
isMixed: false,
},
"const a={};": { hasESM: false, hasCJS: false, isMixed: false },
'// They\'re exposed using "export import" so that types are passed along as expected\nmodule.exports={};':
{ hasESM: false, hasCJS: true, isMixed: false },
};

describe("detectSyntax", () => {