我終於用這個和UglifyJS2Dot/GraphViz,在一種以上的答案相結合的答案和鏈接的問題。
對我而言,缺少的部分是如何過濾解析的AST。事實證明,UglifyJS擁有TreeWalker對象,它基本上將一個函數應用於AST的每個節點。這是我到目前爲止的代碼:我node運行
//to be run using nodejs
var UglifyJS = require('uglify-js')
var fs = require('fs');
var util = require('util');
var file = 'path/to/file...';
//read in the code
var code = fs.readFileSync(file, "utf8");
//parse it to AST
var toplevel = UglifyJS.parse(code);
//open the output DOT file
var out = fs.openSync('path/to/output/file...', 'w');
//output the start of a directed graph in DOT notation
fs.writeSync(out, 'digraph test{\n');
//use a tree walker to examine each node
var walker = new UglifyJS.TreeWalker(function(node){
//check for function calls
if (node instanceof UglifyJS.AST_Call) {
if(node.expression.name !== undefined)
{
//find where the calling function is defined
var p = walker.find_parent(UglifyJS.AST_Defun);
if(p !== undefined)
{
//filter out unneccessary stuff, eg calls to external libraries or constructors
if(node.expression.name == "$" || node.expression.name == "Number" || node.expression.name =="Date")
{
//NOTE: $ is from jquery, and causes problems if it's in the DOT file.
//It's also very frequent, so even replacing it with a safe string
//results in a very cluttered graph
}
else
{
fs.writeSync(out, p.name.name);
fs.writeSync(out, " -> ");
fs.writeSync(out, node.expression.name);
fs.writeSync(out, "\n");
}
}
else
{
//it's a top level function
fs.writeSync(out, node.expression.name);
fs.writeSync(out, "\n");
}
}
}
if(node instanceof UglifyJS.AST_Defun)
{
//defined but not called
fs.writeSync(out, node.name.name);
fs.writeSync(out, "\n");
}
});
//analyse the AST
toplevel.walk(walker);
//finally, write out the closing bracket
fs.writeSync(out, '}');
,然後把輸出通過
dot -Tpng -o graph_name.png dot_file_name.dot
注:
它提供了一個非常基本的圖形 - 只有黑色和白色,沒有格式。
它根本不抓ajax,也可能不是像eval
或with
那樣的東西,如others have mentioned。另外,它在圖中包含:由其他函數調用的函數(以及因此調用其他函數的函數),獨立調用的函數,已定義但未調用的AND函數。
由於這一切,它可能會錯過相關的事情,或包括那些不相關的事情。儘管這是一個開始,並且似乎完成了我之前的任務,而首先是什麼使我想到了這個問題。
+1個不錯的問題 - – miku 2012-04-16 22:09:32
爲什麼不使用支持分析javascript的開發工具? – Tushar 2013-06-30 14:20:43
它看起來原來的線程已經消失,現在鏈接斷開了。 :-( – 2015-09-24 00:46:48