Skip to content

Commit 6dfa624

Browse files
committed
add isESM helper
1 parent e67f129 commit 6dfa624

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

packages/nextjs/src/utils/isESM.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* Determine if the given source code represents a file written using ES6 modules.
3+
*
4+
* The regexes used are from https://github.com/component/is-module, which got them from
5+
* https://github.com/formatjs/js-module-formats, which says it got them from
6+
* https://github.com/ModuleLoader/es-module-loader, though the originals are now nowhere to be found.
7+
*
8+
* @param moduleSource The source code of the module
9+
* @returns True if the module contains ESM-patterned code, false otherwise.
10+
*/
11+
export function isESM(moduleSource: string): boolean {
12+
const importExportRegex =
13+
/(?:^\s*|[}{();,\n]\s*)(import\s+['"]|(import|module)\s+[^"'()\n;]+\s+from\s+['"]|export\s+(\*|\{|default|function|var|const|let|[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))/;
14+
const exportStarRegex = /(?:^\s*|[}{();,\n]\s*)(export\s*\*\s*from\s*(?:'([^']+)'|"([^"]+)"))/;
15+
16+
return importExportRegex.test(moduleSource) || exportStarRegex.test(moduleSource);
17+
}

0 commit comments

Comments
 (0)