使用toString()时如何格式化函数体

时间:2016-03-09 21:04:36

标签: javascript formatting google-chrome-devtools firebug console.log

假设我从缩小的JavaScript文件中获得此功能:

function fn(){console.log('Lorem');console.log('Ipsum');}

我想在调用时获得一个漂亮的打印缩进版本:

console.log(fn.toString());

预期产出:

function fn() {
    console.log('Lorem');
    console.log('Ipsum');
}

而不是:

function fn(){console.log('Lorem');console.log('Ipsum');}

无论如何要做到这一点?

2 个答案:

答案 0 :(得分:3)

JavaScript没有内置函数来执行此操作。因此,如果您想以编程方式进行漂亮的打印,则必须手动完成。 为了获得函数的源代码,有一个非标准的Function.prototype.toSource()函数,但只有Firefox才支持它。一个非常简单的漂亮打印功能覆盖您的示例:

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));

如上所述,不同的开发人员工具集成了选项,可以在调试器中打印JavaScript源代码。

<强>萤火虫:

Firebug pretty print button

Firefox DevTools:

Firefox DevTools pretty print button

Chrome DevTools:

Chrome DevTools pretty print button

答案 1 :(得分:0)

js-beautify库可以很好地打印JS代码

http://jsbeautifier.org/

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');
}