我使用 Rhino 作为 Ant 构建过程的一部分来捆绑和缩小 JavaScript。除此之外,我还想预编译客户端模板,即将它们从标记编译为 JavaScript。乍一看,我认为Rhino的serialize()方法可以做到这一点,但事实似乎并非如此。
// Load templating engine
load( "engine.js" );
// Read template file
var template = readFile( "foo.template" ),
// Compile template
compiled = engine.compile( template );
// Write compiled template to file
serialize( compiled, "compiledFoo.js" );
这会导致写入一个二进制文件。我想要的是一个包含已编译模板的文本文件。
如果使用serialize() 不是答案,那么什么是呢?由于它是 Rhino,因此也可以导入 Java 类。临时,我想不出办法。
我知道这可以在 Node 中完成,但我现在无法将构建过程从 Ant-Rhino 迁移到 Grunt-Node。
最佳答案
在寻找答案的过程中,我 came across事实上,Rhino 的 C/C++ 姐妹 SpiderMonkey 有一个 uneval()
函数,您可以猜到,它的作用与 JavaScript 的 eval()
函数相反。稍后再 Google 搜索一下,I found Rhino 在 1.5R5 中实现了 uneval()
。这可能是提到 Rhino 具有此功能的唯一文档 ( or not )。
话虽如此,解决方案如下:
// Load the templating engine
load( "engine.js" );
// Read the template file
var template = readFile( "foo.template" ),
// Compile the template markup to JavaScript
compiled = engine.compile( template ),
// Un-evaluate the compiled template to text
code = uneval( compiled ),
// Create the file for the code
out = new java.io.FileWriter( "foo.js" );
// Write the code to the file
out.write( code, 0, code.length );
out.flush();
out.close();
quit();
关于java - 如何使用 Rhino shell 将 JavaScript 代码序列化到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11160058/