caoccao / Javet

Javet is Java + V8 (JAVa + V + EighT). It is an awesome way of embedding Node.js and V8 in Java.
https://www.caoccao.com/Javet/
Apache License 2.0
685 stars 65 forks source link

Module Enhancement #370

Open aiselp opened 1 month ago

aiselp commented 1 month ago

When a module is loaded I want to set something on import.meta in the module for the module to use, which by default is just an empty object. The module resolver is set for NodeRuntime, but the import() function does not seem to work. When called, it still goes through the nodejs module callback and throws an error like the following

TypeError [ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING]: A dynamic import callback was not specified.
    at importModuleDynamicallyCallback (node:internal/modules/esm/utils:228:9)

When using import with, such as import fooData from './foo.json' with { type: 'json' }; , it will also be called back by nodejs and imported correctly

caoccao commented 1 month ago

Please leave the complete code.

aiselp commented 1 month ago
V8Host.getNodeInstance().createV8Runtime<NodeRuntime>().use { runtime ->
            runtime.v8ModuleResolver = object : JavetBuiltInModuleResolver() {
                override fun resolve(
                    v8Runtime: V8Runtime?,
                    resourceName: String?,
                    v8ModuleReferrer: IV8Module?
                ): IV8Module? {
                    println("resolve: $resourceName referrer: ${v8ModuleReferrer?.resourceName}")
                    return super.resolve(v8Runtime, resourceName, v8ModuleReferrer)
                }
            }
            runtime.getExecutor("""
                await import("a")
            """.trimIndent()).setModule(true).executeVoid()
        }

image

caoccao commented 1 month ago

This is a typical pitfall in Node.js. Please check this doc out. Sample test code is at here.