d__k d__k - 1 year ago 111
Java Question

Execution uglifyJs2 via Nashorn

I extracted uglifyJs2 via

uglifyjs --self
and I'm trying to minify app.js using uglify.js. I expect, that minified js should be generated into new file or console at least but now it doesn't work. What should I do to minify app.js using uglify.min.js?

public static void main(String[] args) throws Exception {
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");
Bindings bindings = new SimpleBindings();
bindings.put("console", System.console());
executeJs("uglifyjs.min.js",scriptEngine, bindings);
String res = (String) invocable.invokeFunction("UglifyJS.parse(code)", code);
//Here I got NoSuchMethodException: No such function UglifyJS.parse(code)

static String readFile(String path, Charset encoding)
throws IOException
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);

private static void executeJs(String fileName, ScriptEngine engine, Bindings bindings) throws Exception {
String test = readFile(fileName, StandardCharsets.UTF_8);
engine.put(ScriptEngine.FILENAME, fileName);
engine.eval(test, bindings);

When i mo

Answer Source

invokeFunction can be used to invoke only global functions. It can not be used to evaluate arbitrary code like you've above. The following will work:

// define a global function that accepts one arg and invoke UglifyJS.parse on it
scriptEngine.eval("function func(code) { return UglifyJS.parse(code) }");

// call the newly defined global function "func"
invocable.invokeFunction("func", code);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download