如果我运行以下代码,我会得到输出:
simple.js
线程中的异常" main" java.lang.NoSuchMethodException:没有这样的函数定义
如何调用'定义'使用invokeFunction在我的webpack js文件中运行?
Java main:
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);
}
/***/ }
/******/ ]);
答案 0 :(得分:1)
问题似乎是definition
函数未在顶级范围内声明。它在匿名函数内声明(它本身作为参数传递给“main”函数)。无论main函数中发生了什么,definition
函数实际上都是其封闭函数的私有函数(从第45行开始)。
如果要通过Invocable接口调用函数,则必须将其作为函数声明或var语句全局声明(在顶级作用域中)。
答案 1 :(得分:0)
以下是使用invokeMethod
代替invokeFunction
使用webpack内置模块的另一种方法:
val root = engine.eval("root") // 'root' being your output.library
engine.invokeMethod(root, "methodName", ...)