Skip to content

Commit

Permalink
Merge pull request #220 from iambumblehead/resolve-cjs-global-mock
Browse files Browse the repository at this point in the history
resolve cjs global mock issue
  • Loading branch information
iambumblehead authored Jul 30, 2023
2 parents c38fb66 + 33f5ada commit c8076f4
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 7 deletions.
2 changes: 2 additions & 0 deletions src/esmockIsESMRe.js
Original file line number Diff line number Diff line change
@@ -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))/
8 changes: 5 additions & 3 deletions src/esmockLoader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}
Expand Down
6 changes: 2 additions & 4 deletions src/esmockModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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)

Expand Down

0 comments on commit c8076f4

Please sign in to comment.