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

标签 java javascript serialization rhino

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

相关文章:

linux .sh 执行中的 Java 版本问题?

javascript - React 中类外部的函数或变量

php - 组注释不起作用

javascript - PHP - 如何在没有按钮的情况下提交选择菜单

javascript - 在 javascript 中随机执行 1 到 5 秒的函数

django - 如何在我的 HyeprlinkedModelSerializer 中使用自定义序列化器字段

c# - 具有 "self-creating"属性的对象的自定义 JSON 序列化以无限循环结束

java - 使用 JSTL 获取 url 中的域名?

java - Android 是否可以获取用户和设备所在国家/地区的货币代码?

java - 启动一个Android项目