gpt4 book ai didi

java - 通过 Nashorn 执行 uglifyJs2

转载 作者:行者123 更新时间:2023-11-30 08:40:00 25 4
gpt4 key购买 nike

我通过 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);
}

当我去的时候

最佳答案

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

关于java - 通过 Nashorn 执行 uglifyJs2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35892937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com