如何使用命令行美化JavaScript代码? [英] How can I beautify JavaScript code using Command Line?

查看:161
本文介绍了如何使用命令行美化JavaScript代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写批处理脚本以美化JavaScript代码。它需要在 Windows Linux 上工作。

I am writing a batch script in order to beautify JavaScript code. It needs to work on both Windows and Linux.

如何使用命令行工具美化JavaScript代码?

How can I beautify JavaScript code using the command line tools?

推荐答案

首先,选择你喜欢的基于Javascript的Pretty Print / Beautifier。我更喜欢 http:/ /jsbeautifier.org/ ,因为这是我第一次找到的。下载文件 https://github.com /beautify-web/js-beautify/blob/master/js/lib/beautify.js

First, pick your favorite Javascript based Pretty Print/Beautifier. I prefer the one at http://jsbeautifier.org/, because it's what I found first. Downloads its file https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js

其次,下载并安装Mozilla组基于Java的Javascript引擎, Rhino 。 安装有点误导;下载zip文件,解压缩所有内容,将js.jar放在Java类路径中(或OS X上的Library / Java / Extensions)。然后,您可以使用类似于此的调用运行脚本

Second, download and install The Mozilla group's Java based Javascript engine, Rhino. "Install" is a little bit misleading; Download the zip file, extract everything, place js.jar in your Java classpath (or Library/Java/Extensions on OS X). You can then run scripts with an invocation similar to this

java -cp js.jar org.mozilla.javascript.tools.shell.Main name-of-script.js

使用步骤1中的Pretty Print / Beautifier写一个小shell脚本,将在您的javascript文件中读取并通过第一步中的Pretty Print / Beautifier运行它。例如

Use the Pretty Print/Beautifier from step 1 to write a small shell script that will read in your javascript file and run it through the Pretty Print/Beautifier from step one. For example

//original code    
(function() { ... js_beautify code ... }());

//new code
print(global.js_beautify(readFile(arguments[0])));

Rhino为javascript提供了一些额外的有用功能,这些功能在浏览器上下文中并不一定有意义,但是在控制台上下文中执行。函数print执行您期望的操作,并打印出一个字符串。函数readFile接受文件路径字符串作为参数,并返回该文件的内容。

Rhino gives javascript a few extra useful functions that don't necessarily make sense in a browser context, but do in a console context. The function print does what you'd expect, and prints out a string. The function readFile accepts a file path string as an argument and returns the contents of that file.

你会调用上面的东西,比如

You'd invoke the above something like

java -cp js.jar org.mozilla.javascript.tools.shell.Main beautify.js file-to-pp.js

你可以在你的Rhino运行脚本中混合搭配Java和Javascript,所以如果你知道一点Java,那么运行文本流也不会太难。

You can mix and match Java and Javascript in your Rhino run scripts, so if you know a little Java it shouldn't be too hard to get this running with text-streams as well.

这篇关于如何使用命令行美化JavaScript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆