jsbeautifier is the official Python wrapper for the popular js-beautify project, providing JavaScript, HTML, and CSS code formatting and beautification capabilities. It is actively maintained with releases typically aligning with the core JavaScript library, currently at version 1.15.4.
pip install jsbeautifierVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to beautify JavaScript and HTML code using `jsbeautifier`. It shows how to import the necessary functions, create and customize an options object, and apply it to format code strings.
Ensure your environment uses Python 3.7 or higher. Always consult the `python_requires` metadata in the official source distribution or `pyproject.toml` for the most accurate requirement.
Create an options object: `opts = jsbeautifier.default_options(); opts.indent_size = 4; beautified = jsbeautifier.beautify(code, opts)`.
Always consult the changelog of the main `beautify-web/js-beautify` GitHub repository for potential behavioral changes or deprecations when upgrading `jsbeautifier`.
Only `jsbeautifier.beautify()` is available for JavaScript code beautification. For HTML or CSS beautification, consider using alternative Python libraries or tools, as these functionalities are not provided by the `jsbeautifier` package.
Replace calls to `jsbeautifier.html_beautify()` with `jsbeautifier.beautify_html()` and `jsbeautifier.css_beautify()` with `jsbeautifier.beautify_css()`.
Ensure `jsbeautifier` is properly installed and up-to-date by running `pip install --upgrade jsbeautifier`. If the error persists, especially when installing other packages like `cssbeautifier`, try installing `jsbeautifier` first before the dependent package.
Explicitly specify the correct encoding, usually 'utf-8', when reading the input content or opening files.
```python
import jsbeautifier
# When reading from a file
with open('input.js', 'r', encoding='utf-8') as f:
input_code = f.read()
beautified_code = jsbeautifier.beautify(input_code)
# When writing to a file, also specify encoding
with open('output.js', 'w', encoding='utf-8') as f:
f.write(beautified_code)
```Instead of relying on command-line flags, use the programmatic interface of `jsbeautifier` in Python to pass options. You can load configuration from a file manually and then apply it.
```python
import jsbeautifier
import json
# Define options programmatically or load from a file
opts = jsbeautifier.default_options()
opts.indent_size = 2
opts.space_in_empty_paren = True
# Example: If you had a .jsbeautifyrc file
# with open('.jsbeautifyrc', 'r') as f:
# config_from_file = json.load(f)
# for key, value in config_from_file.items():
# setattr(opts, key, value)
code = "function test(){var x=1;}"
beautified_code = jsbeautifier.beautify(code, opts)
print(beautified_code)
```No dependency data recorded yet.