Skip to main content

Overview

The HTML beautifier is available as a named export from the js-beautify package:
const beautify = require('js-beautify').html;
const beautify = require('js-beautify').html_beautify; // legacy alias
For ESM imports:
import beautify from 'js-beautify';

beautify.html(code, options);
The HTML beautifier internally uses the JavaScript and CSS beautifiers to reformat embedded <script> and <style> blocks.

Function signature

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

Parameters

sourceCode
string
required
The HTML source code string to beautify.
options
object
Configuration options object. All keys use underscores.

Return value

result
string
The beautified HTML source code as a string.

Examples

const beautifyHtml = require('js-beautify').html;

const ugly = '<html><head><title>Test</title></head><body><p>Hello <strong>world</strong></p></body></html>';

const pretty = beautifyHtml(ugly, {
  indent_size: 2,
  wrap_line_length: 120,
});

console.log(pretty);
// <html>
//   <head>
//     <title>Test</title>
//   </head>
//   <body>
//     <p>Hello <strong>world</strong></p>
//   </body>
// </html>
Use content_unformatted: ['pre', 'textarea', 'script'] to prevent the beautifier from modifying the content of those elements, which is useful when their whitespace is significant.

Directives

You can control beautifier behavior inline with HTML comments:
<!-- beautify ignore:start -->
<div class="some  weird   spacing"></div>
<!-- beautify ignore:end -->

<!-- beautify preserve:start -->
<ul>
    <li>Item one</li>
    <li>Item two</li>
</ul>
<!-- beautify preserve:end -->
  • ignore — The beautifier treats the enclosed block as literal text and does not parse or reformat it.
  • preserve — The beautifier parses the enclosed block but keeps its existing formatting unchanged.