js-beautify

repository·main·Indexed 27 days ago

https://github.com/beautifier/js-beautify

A tool for reformatting and re-indenting JavaScript, HTML, and CSS code. It supports multiple runtimes including Node.js, Python, and web browsers. It provides a CLI for file processing and a programmatic API for integration, featuring extensive configuration options for indentation, brace styles, and line wrapping, as well as directives to ignore or preserve specific code sections.

Tokens
7.7K
Snippets
20
Records
40
Agent score
94%

What's inside js-beautify

  1. Configure language-specific overrides in JavaScript

    main

    Settings in the JavaScript implementation can be structured as a shallow tree to allow language-specific overrides. Top-level settings apply to all languages unless overridden in a language-specific block (e.g., html, css, or js).

    Example configuration structure:

    {
        "indent_size": 4,
        "html": {
            "end_with_newline": true,
            "js": {
                "indent_size": 2
            }
        }
    }

    In this example, HTML files inherit an indent_size of 4 but set end_with_newline to true. JavaScript code embedded within HTML will inherit the HTML settings but override indent_size to 2.

    {
        "indent_size": 4,
        "html": {
            "end_with_newline": true,
            "js": {
                "indent_size": 2
            },
            "css": {
                "indent_size": 2
            }
        },
        "css": {
            "indent_size": 1
        },
        "js": {
           "preserve-newlines": true
        }
    }
  2. Use Directives to control beautification in source files

    main

    Directives allow you to control the beautifier's behavior directly within your source code using comments.

    Ignore Directive

    Use the ignore directive to prevent the beautifier from parsing a specific section. The content will be treated as literal text.

    • CSS/JS: /* beautify ignore:start */ ... /* beautify ignore:end */
    • HTML: <!-- beautify ignore:start --> ... <!-- beautify ignore:end -->

    Preserve Directive

    Use the preserve directive to parse a section but keep its existing formatting. Note: This works in HTML and JavaScript, but not in CSS.

    • CSS/JS: /* beautify preserve:start */ ... /* beautify preserve:end */
    • HTML: <!-- beautify preserve:start --> ... <!-- beautify preserve:end -->
    // JavaScript Ignore Example
    var a =  1;
    /* beautify ignore:start */
     {
     This is some strange{template language{using open-braces?
    /* beautify ignore:end */
    
    // JavaScript Preserve Example
    /* beautify preserve:start */
    {
        browserName: 'internet explorer',
        platform:    'Windows 7',
        version:     '8'
    }
    /* beautify preserve:end */
  3. Install js-beautify via npm

    main

    You can install the beautifier for Node.js using npm.

    To install the latest stable release locally as a library:

    $ npm install js-beautify

    To install the latest stable release globally (provides the js-beautify executable CLI):

    $ npm -g install js-beautify

    To install beta or RC versions (vNext):

    $ npm install js-beautify@next
  4. Install jsbeautifier via pip

    main

    To install the Python version of the beautifier, use pip. Note that the Python version only supports JavaScript reformatting. For CSS, you must install cssbeautifier separately. This project no longer supports Python 2.

    $ pip install jsbeautifier
  5. Load configuration in JavaScript

    main

    In JavaScript environments, you can provide configuration to the jsbeautify executable via:

    1. Any jsbeautify_-prefixed environment variables.
    2. A JSON-formatted file specified by the --config parameter.
    3. A .jsbeautifyrc file containing JSON data located at any level above the current working directory ($PWD).
  6. Add JS Beautifier as a Web Library

    main

    You can include JS Beautifier in your web page using CDN services like cdnjs. Include the script tags for the specific languages you need (JS, CSS, or HTML).

    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/2.0.3/beautify.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/2.0.3/beautify-css.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/2.0.3/beautify-html.js"></script>
  7. Implement a custom unpacker for Python

    main

    To extend the Python version of jsbeautifier with a custom unpacker, create a new submodule (a Python file) and place it in the same directory as the existing unpackers. The __init__ module will automatically detect and load your unpacker.

    Each unpacker module must implement the following three symbols:

    1. PRIORITY (int): An integer representing the priority of the unpacker. Lower numbers have higher priority. This is used when a source file has been processed by multiple packers.
    2. detect(source) (function): Accepts a source string and returns True if the source is packed, otherwise False.
    3. unpack(source) (function): Accepts a source string and returns the unpacked version. This function must always return valid JavaScript. If the source is not packed, it should return the original source unchanged.

    Other symbols defined in your module will be ignored.

  8. Use the Js-Beautify CLI

    main

    The js-beautify CLI allows you to format JavaScript, CSS, and HTML files from the command line. It supports file patterns (globs), reading from stdin, and writing to specific output files or replacing files in-place.

    Basic Usage:

    • To beautify a single file and output to stdout: js-beautify file.js
    • To beautify a file and overwrite it: js-beautify file.js --replace (or -r)
    • To beautify multiple files using a glob: js-beautify "src/**/*.js" --replace
    • To beautify via stdin: cat file.js | js-beautify
    • To specify an output file: js-beautify file.js --outfile out.js (or -o)

    Configuration:

    • Use --config <path> to specify a custom configuration file.
    • Use --editorconfig to enable .editorconfig support for setting indentation and line endings.
  9. Use JS Beautifier as a Web Library

    main

    Once the script tags are embedded, the library exposes three global functions: js_beautify, css_beautify, and html_beautify.

    const options = { indent_size: 2, space_in_empty_paren: true }
    const dataObj = {completed: false,id: 1,title: "delectus aut autem",userId: 1,}
    const dataJson = JSON.stringify(dataObj)
    
    js_beautify(dataJson, options)
  10. Use jsbeautifier in Python

    main

    You can use the Python library to beautify strings or files. You can also use default_options() to create a configuration object. Configuration option names use underscores instead of dashes (e.g., --indent-size becomes indent_size).

    import jsbeautifier
    
    # Beautify a string
    res = jsbeautifier.beautify('your JavaScript string')
    
    # Beautify a file
    res = jsbeautifier.beautify_file('some_file.js')
    
    # Beautify with options
    opts = jsbeautifier.default_options()
    opts.indent_size = 2
    opts.space_in_empty_paren = True
    res = jsbeautifier.beautify('some JavaScript', opts)
  11. Use the JavaScript API for JS, CSS, and HTML

    main

    You can access the beautifiers programmatically in Node.js. All methods accept two arguments: the string to be beautified and an options object.

    var beautify_js = require('js-beautify'); // also available under "js" export
    var beautify_css = require('js-beautify').css;
    var beautify_html = require('js-beautify').html;
    
    // Usage: beautify_js(codeString, optionsObject);
  12. Use js-beautify as a Node.js library (CommonJS)

    main

    After installing locally, you can import specific beautifier methods for JS, CSS, or HTML. All methods follow the signature beautify(code, options), where code is the string to beautify and options is a configuration object.

    Note: Configuration option names use underscores instead of dashes (e.g., --indent-size becomes indent_size).

    var beautify = require('js-beautify/js').js,
        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 }));
    });