Programing

명령 줄을 사용하여 JavaScript 코드를 어떻게 아름답게 만들 수 있습니까?

lottogame 2020. 8. 30. 19:39
반응형

명령 줄을 사용하여 JavaScript 코드를 어떻게 아름답게 만들 수 있습니까?


JavaScript 코드를 아름답게하기 위해 배치 스크립트를 작성하고 있습니다. WindowsLinux 모두에서 작동해야합니다 .

명령 줄 도구를 사용하여 JavaScript 코드를 어떻게 아름답게 만들 수 있습니까?


먼저, 선호하는 Javascript 기반 Pretty Print / Beautifier를 선택하십시오. 나는 하나를 선호한다http://jsbeautifier.org/ , 제가 ​​처음 찾은 것이기 때문입니다. 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)에 배치합니다. 그런 다음 다음과 유사한 호출로 스크립트를 실행할 수 있습니다.

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

1 단계의 Pretty Print / Beautifier를 사용하여 자바 스크립트 파일을 읽고 1 단계의 Pretty Print / Beautifier를 통해 실행할 작은 셸 스크립트를 작성합니다. 예를 들면

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

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

Rhino는 브라우저 컨텍스트에서는 의미가 없지만 콘솔 컨텍스트에서는 작동하는 몇 가지 유용한 기능을 자바 스크립트에 제공합니다. print 함수는 예상 한대로 수행하고 문자열을 인쇄합니다. readFile 함수는 파일 경로 문자열을 인수로 받아들이고 해당 파일의 내용을 반환합니다.

위의 내용을 다음과 같이 호출합니다.

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

Rhino 실행 스크립트에서 Java와 Javascript를 혼합하고 일치시킬 수 있으므로 약간의 Java를 알고 있다면 텍스트 스트림으로도 실행하는 것이 너무 어렵지 않습니다.


nodejs를 사용하는 경우 uglify-js 를 사용해보십시오

Ubuntu 12.04에서 이미 nodejs가 설치되어 있다고 가정하면 다음을 사용하여 uglify를 설치할 수 있습니다.

sudo npm install -g uglify-js

그런 다음 옵션을 얻습니다.

uglifyjs -h

따라서 foo.js다음과 같은 소스 파일이있는 경우 :

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

이렇게 아름답게 할 수 있습니다.

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

uglify기본적으로 들여 쓰기에 공백을 사용하므로 4 칸 들여 쓰기를 탭으로 변환하려면 unexpandUbuntu 12.04와 함께 제공되는 탭을 실행할 수 있습니다 .

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

또는 한 번에 모든 작업을 수행 할 수 있습니다.

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

여기에서 확장 해제에 대해 자세히 알아볼 수 있습니다.

그래서 결국 나는 다음과 같은 파일로 끝납니다.

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

업데이트 2016-06-07

설치는 동일하지만 uglify-js의 관리자는 현재 버전 2에서 작업하는 것으로 보입니다 .


2014 년 4 월 업데이트 :

미화 기는 2010 년에 대답 한 이후로 다시 작성되었습니다. 이제 거기에는 파이썬 모듈이 있고 nodejs 용 npm 패키지가 있으며 jar 파일은 사라졌습니다. github.com 에서 프로젝트 페이지를 읽어 보세요 .

Python 스타일 :

 $ pip install jsbeautifier

NPM 스타일 :

 $ npm -g install js-beautify

그것을 사용하려면 :

 $ js-beautify file.js

원래 답변

@Alan Storm의 답변에 추가

http://jsbeautifier.org/기반으로하는 명령 줄 미화 기는 사용하기가 조금 더 쉬워졌습니다. rhino (자바 기반 JS 엔진, 패키지화) 대신 V8 자바 스크립트 엔진 (c ++ 코드)을 기반으로하기 때문입니다. "js.jar"). 따라서 rhino 대신 V8을 사용할 수 있습니다.

사용하는 방법:

download jsbeautifier.org zip file from http://github.com/einars/js-beautify/zipball/master

(this is a download URL linked to a zip file such as http://download.github.com/einars-js-beautify-10384df.zip)

old (no longer works, jar file is gone)

  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

  ./jsbeautify somefile.js

-has slightly different command line options than the rhino version,

-and works great in Eclipse when configured as an "External Tool"


On Ubuntu 18.04 LTS

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

In the console, you can use Artistic Style (a.k.a. AStyle) with --mode=java.
It works great and it's free, open-source and cross-platform (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. 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).

The code is located at https://github.com/belgampaul/JsBeautifier

I used rhino and beautifier.js

USAGE from console: java -jar jsbeautifier.jar script indentation

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

USAGE from java code: 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.

In the hope it'll save you some time in your project.


I've written an article explaining how to build a command-line JavaScript beautifier implemented in JavaScript in under 5 minutes. YMMV.

  1. Download the latest stable Rhino and unpack it somewhere, e.g. ~/dev/javascript/rhino
  2. Download beautify.js which is referenced from aforementioned jsbeautifier.org then copy it somewhere, e.g. ~/dev/javascript/bin/cli-beautifier.js
  3. Add this at the end of beautify.js (using some additional top-level properties to 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, e.g. ~/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.


I believe when you asked about command line tool you just wanted to beautify all your js files in batch.

In this case Intellij IDEA (tested with 11.5) can do this.

You just need to select any of your project files and select "Code"->"Reformat code.." in main IDE menu. Then in the dialog select "all files in directory ..." and press "enter". Just make sure you dedicated enough memory for the JVM.


Use the modern JavaScript way:

Use Grunt in combination with the jsbeautifier plugin for Grunt

You can install everything easily into your dev environment using 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.

참고URL : https://stackoverflow.com/questions/18985/how-can-i-beautify-javascript-code-using-command-line

반응형