通过Nashorn执行uglifyJs2

时间:2016-03-09 13:27:44

标签: java nashorn

我通过uglifyjs --self提取了uglifyJs2,并尝试使用uglify.js缩小app.js。我希望,至少应该将缩小的js生成到新文件或控制台中,但现在它不起作用。我该怎么做才能使用uglify.min.js缩小app.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);
}

当我莫

2 个答案:

答案 0 :(得分:2)

invokeFunction可用于仅调用全局函数。它不能用于评估像您一样的任意代码。以下内容适用:

// 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);

答案 1 :(得分:0)

作为另类......

d.map { |a| "%s, %s" % a }
  #=> ["Head 1, f 88", "Head 4, t 88", "Head 33, v 88",
  #    "Head 32, n 88", "Head 32, b 88"] 

在我的系统上的100,000次uglify.callMember(...)调用中,它看起来有点慢,大约慢150ms。首先调用uglify.getMember(“parse”)并直接在该对象上使用调用,似乎没有任何改进。

但它确实避免了命名冲突