Skip to main content

Installation

npm install js-beautify

Importing

Choose between CommonJS require and ESM import depending on your project setup.
// Default export beautifies JavaScript
var beautify = require('js-beautify');

// Named exports for each language
var beautify_js   = require('js-beautify').js;
var beautify_css  = require('js-beautify').css;
var beautify_html = require('js-beautify').html;

// Subpath imports are also supported
var beautify_js = require('js-beautify/js').js;

API

All three beautifier methods share the same signature:
beautify(code, options)
ParameterTypeDescription
codestringThe source code string to beautify
optionsobjectConfiguration options (optional)
Option names match the CLI flag names with hyphens replaced by underscores. For example, --indent-size 2 --space-in-empty-paren becomes { indent_size: 2, space_in_empty_paren: true }.

Examples

JavaScript

var beautify = require('js-beautify');

var ugly = 'function foo(a,b){return a+b;}';
var result = beautify(ugly, { indent_size: 2 });

console.log(result);
// function foo(a, b) {
//   return a + b;
// }
You can also read from a file:
var beautify = require('js-beautify/js').js;
var fs = require('fs');

fs.readFile('foo.js', 'utf8', function(err, data) {
  if (err) throw err;
  console.log(beautify(data, { indent_size: 2, space_in_empty_paren: true }));
});

CSS

var beautify_css = require('js-beautify').css;

var ugly = '.foo{color:red;background:blue;}';
var result = beautify_css(ugly, { indent_size: 2 });

console.log(result);
// .foo {
//   color: red;
//   background: blue;
// }

HTML

var beautify_html = require('js-beautify').html;

var ugly = '<div><p>Hello <strong>world</strong></p></div>';
var result = beautify_html(ugly, { indent_size: 2 });

console.log(result);
// <div>
//   <p>Hello <strong>world</strong></p>
// </div>

Legacy Aliases

The following legacy aliases exist for backwards compatibility. Prefer the shorter .js, .css, and .html names in new code.
var beautify = require('js-beautify');

// These are equivalent to .js, .css, and .html respectively
beautify.js_beautify(code, options);
beautify.css_beautify(code, options);
beautify.html_beautify(code, options);

Common Options

OptionDefaultDescription
indent_size4Number of spaces per indentation level
indent_char" "Character used for indentation
indent_with_tabsfalseUse tabs instead of spaces
eol"auto"End-of-line character(s) (auto = detect from file, else \n)
end_with_newlinefalseEnsure the output ends with a newline
preserve_newlinestruePreserve existing blank lines
max_preserve_newlines10Maximum consecutive blank lines to keep
brace_style"collapse"Brace placement style (collapse, expand, end-expand, none)
wrap_line_length0Wrap lines longer than N characters (0 = disabled)