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

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

如果我 运行 下面的代码我得到输出:

simple.js

Exception in thread "main" java.lang.NoSuchMethodException: No such function definition

如何使用 invokeFunction 在我的 webpack js 文件中调用 'definition' 函数?

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", ...)