Skip to content

Commit 0968bc3

Browse files
committed
module: enable existing machinery for import defer
This commit enables deferred module imports by using the corresponding functionality in V8. It also adds a single test, but more test coverage should be added. Refs: https://github.com/tc39/proposal-defer-import-eval
1 parent 6813080 commit 0968bc3

4 files changed

Lines changed: 33 additions & 1 deletion

File tree

src/module_wrap.cc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,8 @@ ModulePhase to_phase_constant(ModuleImportPhase phase) {
555555
switch (phase) {
556556
case ModuleImportPhase::kEvaluation:
557557
return kEvaluationPhase;
558+
case ModuleImportPhase::kDefer:
559+
return kDeferPhase;
558560
case ModuleImportPhase::kSource:
559561
return kSourcePhase;
560562
default:
@@ -1682,6 +1684,7 @@ void ModuleWrap::CreatePerContextProperties(Local<Object> target,
16821684
V(Module::Status, kErrored);
16831685

16841686
V(ModulePhase, kEvaluationPhase);
1687+
V(ModulePhase, kDeferPhase);
16851688
V(ModulePhase, kSourcePhase);
16861689
#undef V
16871690
}

src/module_wrap.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ enum HostDefinedOptions : int {
3535

3636
enum ModulePhase : int {
3737
kSourcePhase = 1,
38-
kEvaluationPhase = 2,
38+
kDeferPhase = 2,
39+
kEvaluationPhase = 3,
3940
};
4041

4142
/**
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
if (!globalThis.eval_list) {
2+
globalThis.eval_list = [];
3+
}
4+
globalThis.eval_list.push('defer-1');
5+
6+
export const foo = 42;
7+
8+
console.log('executed');
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Flags: --js-defer-import-eval
2+
3+
// Tests that defer import actually evaluates the imported module
4+
// only when properties that it exports are accessed.
5+
6+
import * as assert from 'assert'
7+
8+
globalThis.eval_list = [];
9+
10+
import defer * as deferred from './module-deferred-eval.mjs'
11+
12+
assert.strictEqual(0, globalThis.eval_list.length);
13+
14+
// Attempts to define a property on the deferred module. This should
15+
// trigger its execution, similar to accessing the `foo` property.
16+
assert.throws(() => Object.defineProperty(deferred, 'newProp', {value: 15}), TypeError);
17+
assert.equal(42, deferred.foo);
18+
19+
// Check that the module has been evaluated at this point.
20+
assert.partialDeepStrictEqual(['defer-1'], globalThis.eval_list);

0 commit comments

Comments
 (0)