繁体   English   中英

如何使用Webpack js文件从Nashorn调用方法?

[英]How can I invoke a method from Nashorn with a webpack js file?

如果我运行以下代码,则会得到输出:

simple.js

线程“主”中的异常java.lang.NoSuchMethodException:没有此类函数定义

如何使用invokeFunction在Webpack js文件中调用“定义”功能?

Java主:

public static void main(String[] args) throws ScriptException, NoSuchMethodException {
        ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("nashorn");

        Compilable jsCompilable = (Compilable) jsEngine;
        CompiledScript jsScript = jsCompilable.compile(getBasicScript());

        ScriptContext scriptCtxt = jsEngine.getContext();
        Bindings engineScope = scriptCtxt.getBindings(ScriptContext.ENGINE_SCOPE);
        jsScript.eval(engineScope);

        Invocable jsInvocable = (Invocable) jsEngine;
        jsInvocable.invokeFunction("definition", "mark");
    }    

在getBasicScript()中调用的Webpack文件:

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};

/******/    // The require function
/******/    function __webpack_require__(moduleId) {

/******/        // Check if module is in cache
/******/        if(installedModules[moduleId])
/******/            return installedModules[moduleId].exports;

/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            exports: {},
/******/            id: moduleId,
/******/            loaded: false
/******/        };

/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/        // Flag the module as loaded
/******/        module.loaded = true;

/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }


/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;

/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;

/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";

/******/    // Load entry module and return exports
/******/    return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {

    print('simple.js'); 

    function definition(name) { 
        print('Hello: ' + name); 
    }

/***/ }
/******/ ]);

问题似乎是definition函数未在顶级范围内声明。 它在一个匿名函数内声明(它本身作为参数传递给“ main”函数)。 不管主函数发生什么, definition函数实际上都是对其封闭函数专有的(从第45行开始)。

如果要通过Invocable接口调用函数,则必须以函数声明或var语句在全局(顶级范围)中声明该函数。

这是使用使用webpack构建的模块的另一种方法,该模块使用invokeMethod代替invokeFunction

val root = engine.eval("root") // 'root' being your output.library
engine.invokeMethod(root, "methodName", ...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM