How to implement dynamic module import in an embedding?

I’m hoping that someone can help me with how to implement dynamic module import in an embedding.

Following the example at I have successfully implemented ES6 modules in my embedding.
However, this is using static module importing. How do I implement dynamic module importing as well?
Looking in the Modules.h include file I can see that there are two API functions SetModuleDynamicImportHook and FinishDynamicModuleImport

extern JS_PUBLIC_API void SetModuleDynamicImportHook(
JSRuntime* rt, ModuleDynamicImportHook func);

extern JS_PUBLIC_API bool FinishDynamicModuleImport(
JSContext* cx, Handle referencingPrivate,
Handle<JSString*> specifier, Handle<JSObject*> promise);

ModuleDynamicImportHook looks similar to ModuleResolveHook in the static case but it looks like it is somehow using a promise object. Can anyone point me towards an example or explain to me how I should use it?
I also don’t understand when (or if) I should call FinishDynamicModuleImport

If anybody can assist I would be very grateful.

Many thanks


Actually I might have managed to answer this myself. It looks like there is an example in js/src/shell/ModuleLoader.cpp that I can work through.
Apologies for the silly question…

Hi Miles,

Not a silly question. The idea is that the dynamic import hook loads, instantiates and evaluates the requested module. It must eventually call FinishDynamicModuleImport (including on failure), passing the referencingPrivate, moduleRequest and promise parameters originally passed to the hook. On success the engine will then call the main module resolve hook to get the imported module.

Hope this helps,


In case it helps to have an example, you can see GJS’s dynamic import hook at the bottom of this file: