繁体   English   中英

如何使用Rhino shell将JavaScript代码序列化为文件?

[英]How can I serialize JavaScript code to a file using Rhino shell?

我使用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。

在我寻找答案的过程中,我发现 Rhino的C / C ++姐妹SpiderMonkey有一个uneval()函数,你可以猜测它与JavaScript的eval()函数相反。 之后uneval()谷歌搜索, 我发现 Rhino在1.5R5中实现了uneval() 这可能是唯一提及Rhino具有此功能的文档( 或不具备 )。

话虽这么说,这是解决方案:

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

在javascript中编写一个函数,您可以从Java调用该函数,返回您需要的值作为字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM