I am writing a batch script in order to beautify JavaScript code. It needs to work on both Windows and Linux.
How can I beautify JavaScript code using the command line tools?
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
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
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 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
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.
UPDATE April 2014:
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. Please read the project page on github.com.
Python style:
$ pip install jsbeautifier
NPM style:
$ npm -g install js-beautify
to use it (this will return the beatified js file on the terminal, the main file remains unchanged):
$ js-beautify file.js
To make the changes take effect on the file, you should use this command:
$ js-beautify -r file.js
Original answer
Adding to Answer of #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"). So you can use V8 instead of rhino.
How to use:
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"
If you're using nodejs then try uglify-js
On Linux or Mac, assuming you already have nodejs installed, you can install uglify with:
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 -- 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:
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
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
It appears that the maintainer of uglify-js is now working on version 2 though installation is the same.
On 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
You have a few one liner choices. Use with npm or standalone with npx.
Semistandar
npx semistandard "js/**/*.js" --fix
Standard
npx standard "js/**/*.js" --fix
Prettier
npx prettier --single-quote --write --trailing-comma all "js/**/*.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).
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.
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.
Download the latest stable Rhino and unpack it somewhere, e.g. ~/dev/javascript/rhino
Download beautify.js which is referenced from aforementioned jsbeautifier.org then copy it somewhere, e.g. ~/dev/javascript/bin/cli-beautifier.js
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] )));
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 $*
(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.
Related
Is it possible to run a JavaScript file with node.js on windows? I have been trying to for hours and can't find any more solutions on the internet that work.
I have a js-file that uses scribbletune which only works with node.js.
I have node.js installed and I installed gitbash because it was recommended in a forum.
I tried to run from command prompt and gitbash but nothing seems to happen.
What am I doing wrong? Any help would be very much appreciated.
There is no need to install gitbash to use Node on Windows. It's a handy thing to have if you're used to a *nix environment. If you're not, it just gives you something more to learn, which isn't helpful if you're already in the middle of trying to learn Node.
Just:
Get the Windows installer from https://nodejs.org/en/download/
Run the Windows installer
Create a directory for your project
Open a Command Prompt Window to get a command line
Switch to your project directory
(Optional, but a good idea) Use npm init to create a package.json file (it'll walk you through it)
Install any libs you're going to be using via npm (for instance, npm install scribbletune from your command prompt window)
Put your JavaScript files in that directory
Use node main.js at the command line to run your main file (whatever it's called; main.js is just a placeholder)
Inorder to run a js (java script file) file
step 1. u need to go to the file location where u want to run.
step 2. just use "shift +right click".
u will see a pop-up and go to powershell or cmd.
step 3. type "node FILENAME.js"
final step: you will see the result ^.^
I have a sample code and saved it to a file such as hello.ts
After installing nodejs on windows use below command for installing typescript
npm install -g typescript
How can I compile hello.ts with node.js directly?
When I install "TypeScript 1.6 in VS2015" and use tsc.exe don't have any problem but I want to use node.js instead of VS 2015 extension
Please guide me generate .js and .ds through Node.js
Run tsc in the command line, you'll have the help page. Compiling a script is easy, just tsc hello.ts in the folder containing your script, you'll get a hello.js file.
Please guide me generate .js and .ds through Node.js
You have two options:
Run tsc.js as a node script
Use typescript as an npm module
Run node tsc.js
This is the approach taken by some tools e.g grunt-ts. You basically just call spawn on the current process process.execPath passing in the other commands as args (-d).
One sample
Run TypeScript as a node module
If you are playing with the typescript compiler API highly recommend NTypeScript See the Readme for reasons.
The TypeScript compiler provides a simple function called transpile that you can use to get the expected output and then write it out to disk yourself.
PS: I have some docs on the TypeScript compiler internals here : https://basarat.gitbooks.io/typescript/content/docs/compiler/overview.html
My preferred way to get going is to use typescript-require.
this library basically adds nodejs support for typescript.
your index file should be a javascript file and it will look like this
require('typescript-require');
require('./src/main.ts');
and main.ts is a typescript file.
Here's a programatically way from TS/Node to run the equivalent of tsc from within a code itself (Note: this uses the TypeScript Compiler API):
https://gist.github.com/rnag/0d8fe2e72dc7b48743c13f9ca8837a4c
I'm using node-jasmine 2 beta4 and writing in coffeescript. I'm happily running tests in Intellij 13.1 having setup the following Run Configuration
Node interpreter: /usr/local/bin/node
Working Dir: [Project Directory]
Javascript File: node_modules/jasmine-node/bin/jasmine-node
Application Parameters: --coffee --verbose spec
I also have setup file watchers for all my coffeescript files and they are building correctly and put into a [Project Directory]/.build subdirectory
Great! But setting breakpoints when debugging is not working. The information sent back to Intellij seems to reference the javascript files given the line numbers I am seeing suggesting that sourcemaps are not being referenced correctly.
Can anyone help?
(Currently i make do by adding a debugger statement instead of intellij's breakpoints)
I think your Javascript file should be node_modules/jasmine-node/lib/jasmine-node/cli.js. The jasmine-node documentation recommends using the cli.js file when using node directly instead of NPM (look under Usage).
I found out about TypeScript, and installed the Visual Studio 2012 Plugin, downloaded the source code and ran the first sample after referencing the .ts file in my HTML document:
function Greeter(person) {
return "Hello, " + person + ".";
}
var user = "James Kent";
document.body.innerHTML = Greeter(user);
And then proceeded to compile the code at the command-line, with:
tsc greeter.ts
But I could not compile it, as Visual Studio says:
Command "tsc" is not valid.
After looking all over the TypeScript website, I was unable to find any information about how to get it working. A Google search also yielded no relevant results.
How can I get TypeScript working?
Update: Running any of the samples provided with the source code simply displays a blank page in any browser. However, samples appear to work just fine on the TypeScript website.
Your system cannot find the path to the compiler. The compiler executable is here (on my x64 Win 8 system) if you want to register it yourself.
C:\Program Files (x86)\Microsoft SDKs\TypeScript\0.8.0.0\
Use it to compile the .ts file to a .js, and use that in your html instead of trying to compile it directly in the browser. That would be really slow.
You can look at the "HTML Application with TypeScript" project in VS, it is configured to compile your TypeScript at the project build.
A simple way to get tsc working on the command line is using nodejs and the corresponding package manager npm. You can get them from nodejs.org. Once you have set up nodejs, all you have to do is install the compiler with
npm install -g typescript
Executing Typescript directly in the browser is rather complicated. Typescript compiles to Javascript, so what you want is reference the compiled code in your html.
In my project, for example, I have this structure:
/public/js/src/ /* many jquery plugins there */
/public/css/src/ /* many css files there, that describe different things */
After changes have been made, I would like to type in command line something like:
root#hostname:/var/www/test/public# ./build
which would generate two files:
/public/css/build.css - all files from /public/css/src/ folder with minified source
/public/js/build.js - all files from /public/js/src folder with minified source
For the moment I am using less css, which is working on node. I would like to have one script that will do everything, for css as for javascript. Could you please advise the best way to "build" dev-source javascript & css files?
You can use YUI Compressor. I'm sure it's also available for Linux.
It works from the command line. Read here how it works.
Example:
java -jar yuicompressor-x.y.z.jar myfile.js -o myfile-min.js --charset utf-8
I'm sure you can setup a simple Bash script that executes two commands, one for CSS and one for JS by using parameters as input.
YUI-Compressor is available as a package in any Ubuntu version.
apt-get install yui-compressor
Hope it helps
You can use Apache ANT and YUI Compressor to set up your own build process. You can minify all your JS and CSS files with a single command.
EDIT: if you want a sample project try H5bp's ant build scripts http://html5boilerplate.com/
I know this is an old question, but for those getting here through Google. You can easily use Compass for this.
compass compile --output-style compressed --force
More info: http://compass-style.org/help/tutorials/production-css/
Use ACCSS for css compression, its compression rate is better than YUI-Compressors and its written in c with automake installation, so it is portable to almost every system.
Like above, you can use a shell script to combine less and accss. accss support reading from stdin, so you can combine them with
lessc styles.less | accss > out.css
It also has severeal compatibility options, especially for Internet Explorer.
https://github.com/acwtools/accss