问题
I need to parse (and possibly modify) a js expression from within javascript (Specifically i want to markup some eval() expressions before the actual eval)
I really like the UglifyJS README examples, but alas, it needs node.js Is there any way to get this to run on clientside browser?!
(i am not really a js expert so if i am completely misunderstanding this platform thingy please let me know)
Failing that, is there an alternative js parser ? Currently i am looking LintJS or esprima or something like that
回答1:
UglifyJS works in both the browser and NodeJS, like Esprima does (best to double check the browser compatibility specs though for each). In fact you can play around with UglifyJS in the browser (Chrome preferred) by going to the UglifyJS site and opening your inspector console and typing:
var ast = UglifyJS.parse("var foo= 1")
Then you can explore the AST data. For example to get the name of the variable declaration use:
ast.body[0].definitions[0].name.name // returns "foo"
If you want to modify the AST tree then study the structure and generate your own AST nodes to extend the tree. The UglifyJS documentation is ok, and the format to study the structure is a little hand-rolled (pop-up dialogs get a little annoying, I had to write my own documentation parser to create docs I could enjoy studying more). The AST nodes are just simple objects (no need for constructors or prototypes, just object literals with simple property values or sub objects/arrays of objects), as long as they have all the required properties and AST structures you'll have a valid AST tree. For example you could change the variable name like this:
ast.body[0].definitions[0].name.name = "bar";
After modifying the tree, you can then print it back into Javascript source with the code generator feature. Like this:
// assuming variable ast already exists from above
var stream = UglifyJS.OutputStream(); // there are options you can pass to control basic formatting
ast.print(stream);
var code = stream.toString();
console.log(code); // equals "var bar=1;"
UglifyJS is great, so is Esprima. Esprima uses the Spider Monkey AST format which is a well known AST standard for Javascript, Uglify uses it's own AST model. I find that Esprima's AST format is clean but verbose, while UglifyJS is shorter but not sure if it's cleaner. There are also tools for Esprima like Escodegen to generate code, like UglifyJS does.
Best to explore them all and see where you feel comfortable, they all do similar great things and allow you to automate your re-factoring and code analysis tasks like never before.
来源:https://stackoverflow.com/questions/17424728/uglifyjs-on-client-side-javascript-or-an-alternative-parser