我正在尝试将 requireJS 与 GraalVM(Polyglot API)一起使用,以在我的来宾语言脚本中加载外部 JS 代码。我要解决的方法是首先在上下文中运行 requirejs:
Context importCtx = Context.create();
String libraryUrl = "file:/require.js";
Source librarySource = Source.newBuilder("js", new URL(libraryUrl)).build();
importCtx.eval(librarySource);
这导致 require 被添加到 JS 全局,这允许我在以下运行相同上下文的 JS 脚本中使用它。然后我只需运行我的来宾脚本:
String scriptUrl = "test.js";
Source scriptSource = Source.newBuilder("js", new URL(scriptUrl)).build();
importCtx.eval(scriptSource);
我的来宾脚本如下所示:
console.log("start of script");
require(['http://momentjs.com/downloads/moment.js'], function(mom) {
console.log("inside require function");
debugger;
console.log(mom.now();
});
debugger;
console.log("end of script");
在浏览器中运行此脚本时,它可以正常工作并打印 moment.now() 的值。但是,当从 Polyglot API 运行它时,JS 运行,require 设置正确,但 function(mom){} 永远不会被调用。基本上我从来没有看到“inside require function”消息和 moment.now() 的值。
我有一种感觉,这是因为加载外部资源时发生错误(我也尝试加载文件而不是远程 URL,但没有运气)。但是,即使在启用了检查选项的情况下运行 chrome devtools,我也看不到任何错误。
可能是什么问题呢?谢谢。