Skip to content

Commit b58092e

Browse files
authored
fix: handling of circular dependencies (#181)
1 parent 341ada1 commit b58092e

File tree

4 files changed

+32
-5
lines changed

4 files changed

+32
-5
lines changed

hook.js

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,12 @@ async function processModule ({ srcUrl, context, parentGetSource, parentResolve,
253253
}
254254
} else {
255255
addSetter(n, `
256-
let $${n} = _.${n}
256+
let $${n}
257+
try {
258+
$${n} = _.${n} = namespace.${n}
259+
} catch (err) {
260+
if (!(err instanceof ReferenceError)) throw err
261+
}
257262
export { $${n} as ${n} }
258263
set.${n} = (v) => {
259264
$${n} = v
@@ -404,10 +409,7 @@ import { register } from '${iitmURL}'
404409
import * as namespace from ${JSON.stringify(realUrl)}
405410
406411
// Mimic a Module object (https://tc39.es/ecma262/#sec-module-namespace-objects).
407-
const _ = Object.assign(
408-
Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } }),
409-
namespace
410-
)
412+
const _ = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } })
411413
const set = {}
412414
const get = {}
413415

test/fixtures/circular-a.mjs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { bar } from './circular-b.mjs'
2+
3+
export const foo = 1
4+
5+
export { bar }

test/fixtures/circular-b.mjs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { foo } from './circular-a.mjs'
2+
3+
export const bar = foo + 1

test/register/v18.19-circular.mjs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { register } from 'module'
2+
import Hook from '../../index.js'
3+
import { strictEqual } from 'assert'
4+
5+
register('../../hook.mjs', import.meta.url)
6+
7+
let bar
8+
9+
Hook((exports, name) => {
10+
if (name.match(/circular-b.mjs/)) {
11+
bar = exports.bar
12+
}
13+
})
14+
15+
await import('../fixtures/circular-b.mjs')
16+
17+
strictEqual(bar, 2)

0 commit comments

Comments
 (0)