Skip to content

Commit e1c5964

Browse files
committed
fix
2 parents dce3ba1 + 402d480 commit e1c5964

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

lib/util/import-or-require.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,23 @@ const importOrRequire = async path => {
1414
let content = {}
1515
try {
1616
content = require(path)
17+
// this is for node 22+
18+
// istanbul ignore next
19+
/* c8 ignore start */
20+
if (content.__esModule) {
21+
return content.default
22+
}
23+
/* c8 ignore end */
1724
} catch {
1825
try {
19-
content = await import(pathToFileURL(path)).then(r => r.default)
20-
/* c8 ignore start */
26+
// this is for node under 20
27+
const results = await import(pathToFileURL(path))
28+
// istanbul ignore next
29+
return results.default
2130
} catch {
2231
// its ok if this fails since the content dir might only be to provide
2332
// other files. the index.js is optional
2433
}
25-
/* c8 ignore end */
2634
}
2735
importOrRequireCache.set(path, content)
2836
return content

test/apply/import-or-require.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const t = require('tap')
2+
const importOrRequire = require('../../lib/util/import-or-require.js')
3+
const path = require('path')
4+
5+
t.test('importOrRequire', async t => {
6+
const dir = t.testdir({
7+
esm: {
8+
'package.json': JSON.stringify({
9+
type: 'module',
10+
}),
11+
'index.js': 'export default "type module";',
12+
},
13+
'esm.js': 'export default "esm";',
14+
'mjs.mjs': 'export default "mjs";',
15+
'cjs.cjs': 'module.exports = "cjs";',
16+
'js.js': 'module.exports = "js";',
17+
'invalid.js': 'invalid',
18+
})
19+
20+
await Promise.all(
21+
// double 'js' triggers the cache
22+
['mjs', 'cjs', 'js', 'js'].map(async type => {
23+
const output = await importOrRequire(path.join(dir, `${type}.${type}`))
24+
t.same(output, type)
25+
}),
26+
)
27+
})

0 commit comments

Comments
 (0)