2

比方說,我有一個精縮JavaScript文件這一功能:使用的toString時如何格式化函數體()

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

無論如何要做到這一點?

回答

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

火狐DevTools:

Firefox DevTools pretty print button

Chrome的DevTools:

Chrome DevTools pretty print button

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'); 
} 
相關問題