简体   繁体   English

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

[英]How can I beautify JavaScript code using Command Line?

I am writing a batch script in order to beautify JavaScript code.我正在编写批处理脚本以美化 JavaScript 代码。 It needs to work on both Windows and Linux .它需要在WindowsLinux 上运行

How can I beautify JavaScript code using the command line tools?如何使用命令行工具美化 JavaScript 代码?

First, pick your favorite Javascript based Pretty Print/Beautifier.首先,选择您最喜欢的基于 Javascript 的 Pretty Print/Beautifier。 I prefer the one at我更喜欢在http://jsbeautifier.org/ , because it's what I found first. http://jsbeautifier.org/ ,因为这是我首先发现的。 Downloads its file https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js下载其文件https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js

Second, download and install The Mozilla group's Java based Javascript engine, Rhino .其次,下载并安装 Mozilla 集团基于 Java 的 Javascript 引擎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).下载 zip 文件,解压缩所有内容,将 js.jar 放在您的 Java 类路径(或 OS X 上的 Library/Java/Extensions)中。 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

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.使用步骤 1 中的 Pretty Print/Beautifier 编写一个小的 shell 脚本,该脚本将读取您的 javascript 文件并通过第一步中的 Pretty Print/Beautifier 运行它。 For example例如

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

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

Rhino gives javascript a few extra useful functions that don't necessarily make sense in a browser context, but do in a console context. Rhino 为 javascript 提供了一些额外有用的函数,这些函数在浏览器上下文中不一定有意义,但在控制台上下文中有用。 The function print does what you'd expect, and prints out a string.函数 print 执行您期望的操作,并打印出一个字符串。 The function readFile accepts a file path string as an argument and returns the contents of that file.函数 readFile 接受一个文件路径字符串作为参数并返回该文件的内容。

You'd invoke the above something like你会调用上面的东西

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

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.你可以在你的 Rhino 运行脚本中混合和匹配 Java 和 Javascript,所以如果你知道一点 Java,那么用文本流运行它应该不会太难。

UPDATE April 2014 : 2014 年 4 月更新

The beautifier has been rewritten since I answered this in 2010. There is now a python module in there, an npm Package for nodejs, and the jar file is gone.自从我2010年回答这个问题以来,美化器已经被重写了。现在那里有一个python模块,一个用于nodejs的npm包,jar文件不见了。 Please read the project page on github.com .请阅读github.com 上项目页面

Python style:蟒蛇风格:

 $ pip install jsbeautifier

NPM style: NPM 风格:

 $ npm -g install js-beautify

to use it:使用它:

 $ js-beautify file.js

Original answer原答案

Adding to Answer of @Alan Storm添加到@Alan Storm的答案

the command line beautifier based on http://jsbeautifier.org/ has gotten a bit easier to use, because it is now (alternatively) based on the V8 javascript engine (c++ code) instead of rhino (java-based JS engine, packaged as "js.jar").基于http://jsbeautifier.org/的命令行美化器已经变得更容易使用了,因为它现在(或者)基于 V8 javascript 引擎(c++ 代码)而不是 rhino(基于 java 的 JS 引擎,打包作为“js.jar”)。 So you can use V8 instead of rhino.所以你可以用 V8 代替 Rhino。

How to use:如何使用:

download jsbeautifier.org zip file from http://github.com/einars/js-beautify/zipball/masterhttp://github.com/einars/js-beautify/zipball/master下载 jsbeautifier.org zip 文件

(this is a download URL linked to a zip file such as http://download.github.com/einars-js-beautify-10384df.zip ) (这是链接到 zip 文件的下载 URL,例如http://download.github.com/einars-js-beautify-10384df.zip

old (no longer works, jar file is gone)旧的(不再有效,jar 文件不见了)

  java -jar js.jar  name-of-script.js

new (alternative)新的(替代)

install/compile v8 lib FROM svn, see v8/README.txt in above-mentioned zip file从 svn 安装/编译 v8 lib,参见上述 zip 文件中的 v8/README.txt

  ./jsbeautify somefile.js

-has slightly different command line options than the rhino version, - 与犀牛版本的命令行选项略有不同,

-and works great in Eclipse when configured as an "External Tool" - 配置为“外部工具”时,在 Eclipse 中运行良好

If you're using nodejs then try uglify-js如果您使用的是 nodejs,请尝试 uglify -js

On Linux or Mac, assuming you already have nodejs installed, you can install uglify with:在 Linux 或 Mac 上,假设您已经安装了 nodejs,您可以使用以下命令安装 uglify:

sudo npm install -g uglify-js

And then get the options:然后得到选项:

uglifyjs -h

So if I have a source file foo.js which looks like this:所以如果我有一个看起来像这样的源文件foo.js

// foo.js -- minified
function foo(bar,baz){console.log("something something");return true;}

I can beautify it like so:我可以这样美化它:

uglifyjs foo.js --beautify --output cutefoo.js

uglify uses spaces for indentation by default so if I want to convert the 4-space-indentation to tabs I can run it through unexpand which Ubuntu 12.04 comes with: uglify默认使用空格进行缩进,所以如果我想将 4-space-indentation 转换为制表符,我可以通过unexpand运行它,Ubuntu 12.04 附带:

unexpand --tabs=4 cutefoo.js > cuterfoo.js

Or you can do it all in one go:或者您可以一次性完成所有操作:

uglifyjs foo.js --beautify | unexpand --tabs=4 > cutestfoo.js

You can find out more about unexpand here您可以在此处找到有关 unexpand 的更多信息

so after all this I wind up with a file that looks like so:所以在这一切之后,我最终得到了一个看起来像这样的文件:

function foo(bar, baz) {
    console.log("something something");
    return true;
}

update 2016-06-07更新 2016-06-07

It appears that the maintainer of uglify-js is now working on version 2 though installation is the same.看起来 uglify-js 的维护者现在正在开发版本 2,尽管安装是相同的。

On Ubuntu LTS在 Ubuntu LTS 上

$ sudo apt install jsbeautifier
$ js-beautify ugly.js > beautiful.js

For in place beautifying, any of the follwing commands:对于就地美化,任何以下命令:

$ js-beautify -r file.js
$ js-beautify --replace file.js

In the console, you can use Artistic Style (aka AStyle) with --mode=java .在控制台中,您可以使用带有 --mode --mode=java艺术风格(又名 AStyle)。
It works great and it's free, open-source and cross-platform (Linux, Mac OS X, Windows).它运行良好,而且免费、开源且跨平台(Linux、Mac OS X、Windows)。

I'm not able to add a comment to the accepted answer so that's why you see a post that should have not existed in the first place.我无法对已接受的答案添加评论,这就是为什么您会看到一开始不应该存在的帖子。

Basically I also needed a javascript beautifier in a java code and to my surprise none is available as far as I could find.基本上我还需要一个 java 代码中的 javascript 美化器,令我惊讶的是,据我所知,没有一个可用。 So I coded one myself entirely based on the accepted answer (it wraps the jsbeautifier.org beautifier .js script but is callable from java or the command line).所以我完全根据接受的答案自己编写了一个代码(它包装了 jsbeautifier.org beautifier .js 脚本,但可以从 java 或命令行调用)。

The code is located at https://github.com/belgampaul/JsBeautifier代码位于https://github.com/belgampaul/JsBeautifier

I used rhino and beautifier.js我用犀牛和beautifier.js

USAGE from console: java -jar jsbeautifier.jar script indentation来自控制台的用法:java -jar jsbeautifier.jar 脚本缩进

example: java -jar jsbeautifier.jar "function ff() {return;}" 2示例:java -jar jsbeautifier.jar "function ff() {return;}" 2

USAGE from java code: public static String jsBeautify(String jsCode, int indentSize)来自 java 代码的用法:public static String jsBeautify(String jsCode, int indentSize)

You are welcome to extend the code.欢迎您扩展代码。 In my case I only needed the indentation so I could check the generated javascript while developing.就我而言,我只需要缩进,这样我就可以在开发时检查生成的 javascript。

In the hope it'll save you some time in your project.希望它能为您的项目节省一些时间。

Use the modern JavaScript way:使用现代 JavaScript 方式:

Use Grunt in combination with the jsbeautifier plugin for GruntGruntGruntjsbeautifier 插件结合使用

You can install everything easily into your dev environment using npm .您可以使用npm轻松地将所有内容安装到您的开发环境中。

All you will need is set up a Gruntfile.js with the appropriate tasks, which can also involve file concatenation, lint, uglify, minify etc, and run the grunt command.您所需要的只是使用适当的任务设置 Gruntfile.js,其中还可能涉及文件连接、lint、uglify、minify 等,并运行 grunt 命令。

You have a few one liner choices.您有几种单衬选择。 Use with npm or standalone with npx .与NPM或独立与使用NPX

Semistandar半标准

npx semistandard "js/**/*.js" --fix

Standard标准

npx standard "js/**/*.js" --fix

Prettier更漂亮

npx prettier --single-quote --write --trailing-comma all "js/**/*.js"

I believe when you asked about command line tool you just wanted to beautify all your js files in batch.我相信当您询问命令行工具时,您只是想批量美化所有 js 文件。

In this case Intellij IDEA (tested with 11.5) can do this.在这种情况下,Intellij IDEA(用 11.5 测试)可以做到这一点。

You just need to select any of your project files and select "Code"->"Reformat code.." in main IDE menu.您只需要选择任何项目文件,然后在主 IDE 菜单中选择“代码”->“重新格式化代码..”。 Then in the dialog select "all files in directory ..." and press "enter".然后在对话框中选择“目录中的所有文件...”并按“输入”。 Just make sure you dedicated enough memory for the JVM.只要确保您为 JVM 分配了足够的内存。

I've written an article explaining how to build a command-line JavaScript beautifier implemented in JavaScript in under 5 minutes.我写了一篇文章,解释了如何在 5 分钟内构建在 JavaScript实现命令行 JavaScript 美化器 YMMV.天啊。

  1. Download the latest stable Rhino and unpack it somewhere, eg ~/dev/javascript/rhino下载最新的稳定版 Rhino 并在某处解压,例如 ~/dev/javascript/rhino
  2. Download beautify.js which is referenced from aforementioned jsbeautifier.org then copy it somewhere, eg ~/dev/javascript/bin/cli-beautifier.js下载从上述 jsbeautifier.org 引用的 beautify.js,然后将其复制到某处,例如 ~/dev/javascript/bin/cli-beautifier.js
  3. Add this at the end of beautify.js (using some additional top-level properties to JavaScript):在 beautify.js 的末尾添加这个(使用一些额外的 JavaScript 顶级属性):

     // Run the beautifier on the file passed as the first argument. print( j23s_beautify( readFile( arguments[0] )));
  4. Copy-paste the following code in an executable file, eg ~/dev/javascript/bin/jsbeautifier.sh:将以下代码复制粘贴到可执行文件中,例如 ~/dev/javascript/bin/jsbeautifier.sh:

     #!/bin/sh java -cp ~/dev/javascript/rhino/js.jar org.mozilla.javascript.tools.shell.Main ~/dev/web/javascript/bin/cli-beautifier.js $*
  5. (optional) Add the folder with jsbeautifier.js to PATH or moving to some folder already there. (可选)将带有 jsbeautifier.js 的文件夹添加到 PATH 或移动到已经存在的某个文件夹。

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

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