Introduction to js-beautify
js-beautify is a powerful JavaScript library aimed at making your code look clean and readable. It provides multiple APIs to help format, beautify, and customize the structure of your JavaScript code. Whether you are managing large projects or small snippets, js-beautify can help you keep your codebase neat and maintainable.
Useful API Explanations with Code Snippets
1. Beautify JavaScript Code
The core functionality of js-beautify is to beautify JavaScript code. You can easily achieve this using the js_beautify
function.
const beautify = require('js-beautify').js;
const code = "function hello(){console.log('Hello, World!');}";
const beautifulCode = beautify(code);
console.log(beautifulCode);
2. Beautify HTML Code
js-beautify isn’t limited to JavaScript alone. You can also beautify HTML documents.
const beautifyHTML = require('js-beautify').html;
const htmlCode = "<div><p>Hello</p></div>";
const beautifulHTMLCode = beautifyHTML(htmlCode);
console.log(beautifulHTMLCode);
3. Beautify CSS Code
In addition to JavaScript and HTML, you can use js-beautify to beautify CSS code as well.
const beautifyCSS = require('js-beautify').css;
const cssCode = "body{margin:0;}";
const beautifulCSSCode = beautifyCSS(cssCode);
console.log(beautifulCSSCode);
4. Customize Beautification Options
js-beautify offers various options to customize the beautification process. Here is how you can set the options:
const beautify = require('js-beautify').js;
const options = {
indent_size: 4,
indent_with_tabs: true,
end_with_newline: true
};
const code = "function hello(){console.log('Hello, World!');}";
const beautifulCode = beautify(code, options);
console.log(beautifulCode);
5. Minify JavaScript Code
Besides beautification, you can also minify JavaScript code to make it more compact.
const uglifyJS = require("uglify-js");
const code = "function hello(){console.log('Hello, World!');}";
const minifiedCode = uglifyJS.minify(code).code;
console.log(minifiedCode);
App Example Using js-beautify APIs
Let’s build a small app that takes JavaScript code as input and outputs the beautified version:
const express = require('express');
const bodyParser = require('body-parser');
const beautify = require('js-beautify').js;
const app = express();
app.use(bodyParser.text());
app.post('/beautify', (req, res) => {
const code = req.body;
const beautifulCode = beautify(code, { indent_size: 2, space_in_empty_paren: true });
res.send(beautifulCode);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
This simple application uses the Express framework to create a server that listens on port 3000. It accepts POST requests with JavaScript code and returns the beautified version of the code.
Hash: 5bdf0f7bef9476e003952e5bace7c0bf18511c1d4080408299842c1bf05b67d7