graaljs
graaljs copied to clipboard
[feature request] Inject Java objects as ES6 modules in javascript runtime
Since the release of javascript ES6 (aka ES2015) javascript supports "modules". Currently the only way to inject objects from Java inside javascript is to inject such objects in the global scope of the javascript runtime via
context.getBindings("js").putMember("myInjectedObject", new MyCustomClass());
It would be useful if those Java instances could be provided to the user who writes the javascript code as if they were native javascript modules; e.g., it should be possible to import those objects via an import statement:
import * as myInjectedObject from 'myCustomClassInstance';
myInjectedObject.myCustomMethod(...);
// and maybe even
import { myCustomMethod } from 'myCustomClassInstance';
myCustomMethod(...)
This would have the following benefits:
- it does not pollute the global javascript scope with many objects
- it allows javascript users to have a more "native" and consistent approach
- possibly it could also improve performance (since if a module is not required it will never be imported)
Side note At the moment the workaround to obtain this behaviour is to do this on the Java side:
context.getBindings("js").putMember("_my_injected_object", new MyCustomClass());
and the re-export that object from a custom made es6 module:
export const myInjectedObject = _my_injected_object;
@sir-ion thanks for submitting feature request We will check it out
I submitted a similar request a while back: https://github.com/oracle/graaljs/issues/264
Whilst I currently have a workaround, it's pretty ugly and I'd still love to have this natively supported.