diff --git a/src/esmockIsESMRe.js b/src/esmockIsESMRe.js new file mode 100644 index 00000000..bc02dbd6 --- /dev/null +++ b/src/esmockIsESMRe.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line max-len +export default /(^\s*|[});\n]\s*)(import\s+(['"]|(\*\s+as\s+)?[^"'()\n;]+\s+from\s+['"]|\{)|export\s+\*\s+from\s+["']|export\s+(\{|default|function|class|var|const|let|async\s+function))/ diff --git a/src/esmockLoader.js b/src/esmockLoader.js index d4d097b5..3eac82a7 100644 --- a/src/esmockLoader.js +++ b/src/esmockLoader.js @@ -141,13 +141,15 @@ const load = async (url, context, nextLoad) => { const source = String((await nextLoad(url, context)).source) const hbang = (source.match(hashbangRe) || [])[0] || '' const sourcesafe = hbang ? source.replace(hashbangRe, '') : source + const importexpr = context.format === 'module' + ? `import {${importedNames}} from '${specifier}';` + : `const {${importedNames}} = require('${specifier}');` return { - format: 'module', + format: context.format, shortCircuit: true, responseURL: encodeURI(url), - source: hbang + `import {${importedNames}} from '${specifier}';` - + sourcesafe + source: hbang + importexpr + sourcesafe } } } diff --git a/src/esmockModule.js b/src/esmockModule.js index 0e8b7372..53e87e9a 100644 --- a/src/esmockModule.js +++ b/src/esmockModule.js @@ -2,6 +2,7 @@ import fs from 'fs' import url from 'node:url' import resolvewith from 'resolvewithplus' import esmockErr from './esmockErr.js' +import esmockIsESMRe from './esmockIsESMRe.js' import { esmockTreeIdSet, @@ -65,9 +66,6 @@ const esmockModuleApply = (defLive, def, fileURL) => { return def } -// eslint-disable-next-line max-len -const esmockModuleESMRe = /(^\s*|[});\n]\s*)(import\s+(['"]|(\*\s+as\s+)?[^"'()\n;]+\s+from\s+['"]|\{)|export\s+\*\s+from\s+["']|export\s+(\{|default|function|class|var|const|let|async\s+function))/ - // returns cached results when available const esmockModuleIsESM = (fileURL, isesm) => { isesm = esmockCacheResolvedPathIsESMGet(fileURL) @@ -77,7 +75,7 @@ const esmockModuleIsESM = (fileURL, isesm) => { isesm = !resolvewith.iscoremodule(fileURL) && isDirPathRe.test(fileURL) - && esmockModuleESMRe.test(fs.readFileSync(fileURL, 'utf-8')) + && esmockIsESMRe.test(fs.readFileSync(fileURL, 'utf-8')) esmockCacheResolvedPathIsESMSet(fileURL, isesm)