Skip to main content

Overview

The default export of js-beautify is a function that beautifies JavaScript source code. All three aliases below are equivalent:
const beautify = require('js-beautify');
const beautify = require('js-beautify').js;
const beautify = require('js-beautify').js_beautify;
For ESM imports:
import beautify from 'js-beautify';

beautify.js(code, options);

Function signature

beautify(sourceCode: string, options?: object): string

Parameters

sourceCode
string
required
The JavaScript source code string to beautify. You can also pass minified code, bookmarklets, or scripts packed by Dean Edward’s packer.
options
object
Configuration options object. All keys use underscores (e.g., indent_size). Options loaded from .jsbeautifyrc or environment variables are merged with lower priority than options passed directly here.

Return value

result
string
The beautified JavaScript source code as a string.

Examples

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

const ugly = 'function hello(name){return "Hello, "+name;}';

const pretty = beautify(ugly, {
  indent_size: 2,
  space_in_empty_paren: true,
});

console.log(pretty);
// function hello(name) {
//   return "Hello, " + name;
// }
Configuration option names are the same as CLI flag names but with underscores instead of dashes. For example, --indent-size 2 maps to { indent_size: 2 }.

Configuration loading (Node.js only)

In the Node.js environment, options are resolved from the following sources in priority order (highest to lowest):
  1. Options passed directly to the function
  2. jsbeautify_-prefixed environment variables
  3. A JSON config file specified via --config
  4. A .jsbeautifyrc JSON file found at or above the current working directory

Language-specific overrides

When loading from .jsbeautifyrc, you can scope settings to a specific language using a nested key:
{
  "indent_size": 4,
  "js": {
    "preserve_newlines": true
  },
  "css": {
    "indent_size": 2
  }
}