escodegen
escodegen copied to clipboard
proposal: Add option to wrap all immediately-invoked functions in parentheses
It would be nice if escodegen
will have option which will work similar to this package:
https://github.com/nolanlawson/optimize-js
Why? No additional dependencies is required, no need to iterate through AST-tree twice, no problems with source map and looks like this package is very slow in getting of updates.
ping
This tweak seems to work for me. It wraps IIFE's like
var x = function() { return stuff }();
becomes
var x = (function() { return stuff })();
and leaves alone declared function variables:
var x = function() { return stuff };
diff --git a/escodegen.js b/escodegen.js
index 42c05ae..db129a5 100644
--- a/escodegen.js
+++ b/escodegen.js
@@ -1887,7 +1887,10 @@
if (!(flags & F_ALLOW_CALL)) {
return ['(', result, ')'];
}
- return parenthesize(result, Precedence.Call, precedence);
+ // check if this CallExpression is an IIFE. If so, then always wrap in parens.
+ return (expr.callee.id === null && expr.callee.params.length === 0) ?
+ parenthesize(result, 0, 1) :
+ parenthesize(result, Precedence.Call, precedence);
},
NewExpression: function (expr, precedence, flags) {
Obviously this needs a settable option. But I have some free time tomorrow, and can make a proper pull request.