Reputation: 2410
Let's say I have this function from a minified JavaScript file:
function fn(){console.log('Lorem');console.log('Ipsum');}
I would like to get a pretty print, indented version when calling:
console.log(fn.toString());
Expected output :
function fn() {
console.log('Lorem');
console.log('Ipsum');
}
Instead of:
function fn(){console.log('Lorem');console.log('Ipsum');}
Anyway to do that?
Upvotes: 5
Views: 968
Reputation: 1561
Prettier is popular modern library now commonly used for code formatting in IDEs that can be run programmatically as well:
It's not a direct answer to the question, but I was actually looking at the answers here to figure out how to format a function's .toString()
in HTML, and just found out I can preserve existing whitespace by setting white-space: pre-wrap;
CSS on the HTML element displaying it.
I hadn't read closely enough to notice this question was referring to minified source code and printing to the console specifically, and spent some time trying to use Prettier and outputting it to HTML and then realized my obvious mistake. Maybe this tip will help others mixing this up like me.
Upvotes: 0
Reputation: 2410
There is the js-beautify
library which does a really good job in pretty printing JS code
https://github.com/beautify-web/js-beautify
// Script inclusion
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.6.4/beautify.js', false);
xmlHttp.send(null);
var jsCode = xmlHttp.responseText;
var script = document.createElement("script");
script.innerHTML = jsCode;
document.head.appendChild(script);
// Usage
function fn(){console.log('Lorem');console.log('Ipsum');}
js_beautify(fn.toString());
// Output
function fn() {
console.log('Lorem');
console.log('Ipsum');
}
Upvotes: 0
Reputation: 20125
JavaScript does not have a built-in function to do this. So, if you want to do pretty printing programmatically, you'll have to do it manually.
To get the function´s source, there is a non-standard Function.prototype.toSource()
function, which is only supported by Firefox, though. A very simple pretty-print function covering your example is:
function prettyPrint(source) {
let formattedSource = fn.toSource ? fn.toSource() : "";
// Add line breaks after curly braces and semicolons
formattedSource = formattedSource.replace(/([{};])/g, "$1\n");
// Add space after opening curly brace
formattedSource = formattedSource.replace(/(\S)\{/g, "$1 {");
// Indent lines ending with a semicolon
formattedSource = formattedSource.replace(/^(.*?);/gm, " $1;");
return formattedSource;
}
console.log(prettyPrint(fn));
Having said the above, the different developer tools have integrated options to pretty print the JavaScript sources within their debuggers.
Firebug:
Firefox DevTools:
Chrome DevTools:
Upvotes: 3