2016-07-27 58 views
0

如果我運行下面的代碼,我得到的輸出:我如何從一個webpack js文件調用Nashorn的方法?

simple.js

異常線程 「main」 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"); 
    }  

的WebPack文件稱爲getBasicScript():

/******/ (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); 
    } 

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

回答

1

這個問題似乎是在definition功能沒有在頂層範圍內聲明。它是在一個匿名函數中聲明的(它本身作爲參數傳遞給「main」函數)。無論主函數發生什麼,definition函數對其封閉函數(從第45行開始)實際上是私有的。

如果你想通過Invocable接口調用一個函數,它必須作爲一個函數聲明或者一個var語句全局聲明(在頂層作用域中)。

+0

感謝 - 你是對的:我有JS的命名空間的問題。如果有人發現這一點,爲了讓它工作,我將我的webpack命令更改爲: 'webpack ./simple.js bundle.js --output-library server --output-library-target umd' 然後調用: 'jsInvocable.invokeFunction(「server」,「mark」);' – mryan

0

這裏是另一種方式來使用使用invokeMethod代替invokeFunction一個內置的WebPack模塊:

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