Skip to main content
1

Install JS Beautify

Install the package globally to get the js-beautify, css-beautify, and html-beautify CLI tools, or locally for use as a Node.js library.
npm install -g js-beautify
2

Beautify a file from the CLI

Pass a file path to the beautifier. Output goes to stdout by default.
js-beautify foo.js
To overwrite the file in place:
js-beautify --replace foo.js
For CSS and HTML:
css-beautify styles.css
html-beautify index.html
3

Use as a Node.js library

Require js-beautify and call the appropriate method for each language. All three methods accept (sourceCode: string, options?: object) and return the formatted string.
var beautify = require('js-beautify');

// JavaScript
var uglyJs = 'function foo(x){if(x>0){return x;}else{return -x;}}';
console.log(beautify.js(uglyJs, { indent_size: 2 }));
// function foo(x) {
//   if (x > 0) {
//     return x;
//   } else {
//     return -x;
//   }
// }

// CSS
var uglyCss = 'div{color:red;font-size:14px;}';
console.log(beautify.css(uglyCss, { indent_size: 2 }));
// div {
//   color: red;
//   font-size: 14px;
// }

// HTML
var uglyHtml = '<html><body><p>Hello</p></body></html>';
console.log(beautify.html(uglyHtml, { indent_size: 2 }));
// <html>
//   <body>
//     <p>Hello</p>
//   </body>
// </html>
4

Use from Python

Import jsbeautifier and call beautify() or beautify_file().
import jsbeautifier

# Beautify a string
res = jsbeautifier.beautify('function foo(){return 42;}')
print(res)
# function foo() {
#     return 42;
# }

# Beautify a file
res = jsbeautifier.beautify_file('foo.js')

# With options
opts = jsbeautifier.default_options()
opts.indent_size = 2
opts.space_in_paren = True
res = jsbeautifier.beautify('function foo(x,y){return x+y;}', opts)
The Python jsbeautifier package only supports JavaScript. For CSS, install cssbeautifier separately: pip install cssbeautifier.
5

Use in a web browser

Include the CDN script tags and call the global functions.
<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.15.4/beautify.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.15.4/beautify-css.min.js"></script>
</head>
<body>
  <script>
    var result = js_beautify('function foo(){return 42;}', { indent_size: 2 });
    console.log(result);
  </script>
</body>
</html>
CLI flag names use dashes (e.g., --indent-size), while library and config file option names use underscores (e.g., indent_size). They are otherwise identical.

Next steps

Configuration Options

Explore all 40+ options for controlling indentation, brace style, line wrapping, and more.

.jsbeautifyrc

Store your settings in a project config file automatically picked up by the CLI.

CLI Reference

Full reference for all CLI flags and options.

API Reference

Complete API documentation for the JavaScript, CSS, and HTML beautifier functions.