Skip to main content

Installation

pip install jsbeautifier
The Python jsbeautifier package only reformats JavaScript. It does not support HTML or CSS. For CSS, install the separate cssbeautifier package.

Module

import jsbeautifier

Functions

beautify()

Beautify a JavaScript source string.
jsbeautifier.beautify(source: str, opts=None) -> str
source
str
required
The JavaScript source code string to beautify.
opts
BeautifierOptions
An options object returned by default_options(). If omitted, default options are used.
result
str
The beautified JavaScript source code.

beautify_file()

Read a JavaScript file and return beautified output as a string.
jsbeautifier.beautify_file(file_name: str, opts=None) -> str
file_name
str
required
Path to the JavaScript file. Pass "-" to read from stdin.
opts
BeautifierOptions
An options object returned by default_options().
result
str
The beautified JavaScript source code.

default_options()

Return a BeautifierOptions instance populated with default values.
jsbeautifier.default_options() -> BeautifierOptions
result
BeautifierOptions
A BeautifierOptions object. Mutate its attributes before passing to beautify() or beautify_file().

BeautifierOptions attributes

All attributes mirror the CLI flag names with underscores instead of dashes.

Examples

import jsbeautifier

# Beautify with default options
result = jsbeautifier.beautify('function hello(name){return "Hello, "+name;}')
print(result)
# function hello(name) {
#     return "Hello, " + name;
# }

# Beautify with custom options
opts = jsbeautifier.default_options()
opts.indent_size = 2
opts.space_in_empty_paren = True
opts.end_with_newline = True

result = jsbeautifier.beautify('function foo(){var x=1;return x;}', opts)
print(result)
# function foo() {
#   var x = 1;
#   return x;
# }

# Beautify a file
result = jsbeautifier.beautify_file('app.min.js')
with open('app.js', 'w') as f:
    f.write(result)

# Read from stdin
import sys
result = jsbeautifier.beautify_file('-')  # reads from stdin
sys.stdout.write(result)

CLI (Python)

The jsbeautifier package also installs a js-beautify command:
# Beautify a file
js-beautify app.min.js

# Specify options
js-beautify -s 2 --end-with-newline app.min.js

# Replace in-place
js-beautify -r app.min.js

# Write to a specific output file
js-beautify -o app.js app.min.js
Run js-beautify --help for a full list of CLI flags.