我试图将Duktape用于Android和JavaScript绑定。

我按照https://wiki.duktape.org/HowtoModules.html的说明操作,按照步骤操作,有以下调用代码:

DuktapeContext::DuktapeContext(JavaVM* javaVM)
    : m_context(duk_create_heap(nullptr, nullptr, nullptr, &m_context, fatalErrorHandler))
    , m_objectType(m_javaValues.getObjectType(getEnvFromJavaVM(javaVM))) {
  if (!m_context) {
    throw std::bad_alloc();
  }
  duk_module_duktape_init(m_context); //<~~~ adds support for `require()`
  // Stash the JVM object in the context, so we can find our way back from a Duktape C callback.
  duk_push_global_stash(m_context);
  duk_push_pointer(m_context, javaVM);
  duk_put_prop_string(m_context, -2, JAVA_VM_PROP_NAME);
  duk_pop(m_context);
}


duk_module_duktape_init的定义如下(现成的,我没有编辑):

/* Register `require` as a global function. */
duk_eval_string(ctx,
                "(function(req){"
                "var D=Object.defineProperty;"
                "D(req,'name',{value:'require'});"
                "D(this,'require',{value:req,writable:true,configurable:true});"
                "D(Duktape,'modLoaded',{value:Object.create(null),writable:true,configurable:true});"
                "})");
duk_push_c_function(ctx, duk__require, 1 /*nargs*/);


在我的javascript文件sample.js中,有以下一行:

var mod = require('tester');

当通过Duktape评估脚本时,该脚本将引发异常Caused by: com.squareup.duktape.DuktapeException: TypeError: undefined not callable at JavaScript.eval(调用require()的行)

我还必须实现Duktape.modSearch()功能吗?我以为只要使用require()就可以逃脱?

最佳答案

由于模块的解析和加载取决于平台,因此您需要自己实现该平台。 duktape随附的模块处理仅处理管理已加载的模块并提供require调用(您不需要自己提供此功能)。注册这两个功能很简单(see also the entire code):

// Module loading support.
duk_push_object(_ctx);
duk_push_c_function(_ctx, resolveModule, JSExport::VarArgs);
duk_put_prop_string(_ctx, -2, "resolve");
duk_push_c_function(_ctx, loadModule, JSExport::VarArgs);
duk_put_prop_string(_ctx, -2, "load");
duk_module_node_init(_ctx, normalizeFilename);


实际的分辨率和加载代码要复杂得多。您可以看到完整的代码in the scripting context class

08-19 08:10