I needed recently to work with some JavaScript code to understand how
bookmarklets work in Google Chrome. Unfortunately the js code was often not well formatted and difficult to read.
Problem
How to automatically reformat JavaScript code so it looks beautiful and is easy to read.
Solution
I recommend this online site if you don't need to have this functionality in your editor of choice:
http://jsbeautifier.org/. To enable beautiful code formatting in Sublime you can:
Testing
To test that the node.js and the necessary plugin is installed correctly you can run the node virtual machine and try to import the module:
$ node
> require("js-beautify")
{ [Function]
js: [Function: js_beautify],
css: [Function: css_beautify],
html: [Function],
js_beautify: [Function: js_beautify],
css_beautify: [Function: css_beautify],
html_beautify: [Function] }
>
To test that the plugin is installed successfully in in sublime you can:
- check sublime tree directory
... Sublime2\Data\Packages\CodeFormatter\
To trigger the formatting:
- Menu tools -> Command Palette (Cmd+Shift+P or Ctrl+Shift+P) and type `Format`.
- The default keyboard shortcat is ["ctrl+alt+f"] or
- If you want to run the command from the console
view.run_command("code_formatter")
References
https://sublime.wbond.net/packages/CodeFormatter
http://nodejs.org/
https://npmjs.org/package/js-beautify
http://jsbeautifier.org/
For further info about node.js and the JavaScript virtual machine functionality
http://www.nodebeginner.org/#hello-world
http://stackoverflow.com/questions/2353818/how-do-i-get-started-with-node-js