Monday, April 1, 2013

How to install and run js-beautify, css-beautify and html-beautify on Windows

Lately, I learned about an excellent code beautifier for HTML, CSS and JavaScript called js-beautify. You can try an online version at jsbeautifier.org. The name js-beautify suggests that it can only beautify JavaScript, but the js-beautify package actually consists of three separate tools called js-beautify, css-beautify and html-beautify.
As you may have guessed, css-beautify and html-beautify will beautify HTML and CSS. html-beautify will even beautify nested CSS and JavaScript in an HTML file. However, as the program itself is written in JavaScript, it's not as easy to install and use as other programs. You can't just download an .exe file and run it. Here's how to install and run it on Windows:
  1. Download and install node.js. This is actually a Windows program, not a JavaScript file as the name may suggest. It allows you to download applications written in JavaScript and run them from the Windows command line.
  2. Open a Windows command prompt and type npm install -g js-beautify. This will download and install three tools on your system: js-beautify, css-beautify and html-beautify.
  3. To beautify a JavaScript file, type js-beautify -f input.js -o output.js at the command line. The same goes for css-beautify and html-beautify. Note that html-beautify will also beautify CSS and JavaScript embedded in the HTML file, so it's kind of an all-in-one solution. All three tools also support stdin and stdout (type js-beautify -h for help)
Here's an example where I used html-beautify to clean up an ugly HTML file with CSS and JavaScript.
Before:
<html><head><title>Test</title>
<style>
div.test {    background-color: blue; }
 </style>
<script>
 function test()
   { alert("hello world"    ) ; 
   }
  </script>
</head>
<body><div class="test"></div></body>
</html>
After:
<html>
    <head>
        <title>Test</title>
        <style>
            div.test {
                background-color: blue;
            }
        </style>
        <script>
            function test() {
                alert("hello world");
            }
        </script>
    </head>
    
    <body>
        <div class="test"></div>
    </body>

</html>
Now isn't that beautiful?

No comments:

Post a Comment