问题
I have some code that has the following format:
function myfunc1 () { ... jquery.bind('click', myfunc2) ... }
function myfunc2 () { ... }
...
Yes, the functions are global, but it's ok since I'm writing within a google chrome extension content script, so it's sandboxed.
Now, I'm trying to minify and obfuscate the code. I've tried YUI Compressor and the Google Closure compiler. The problem is, I can't figure out how to minify/obfuscate the global function names. With YUI it doesn't minify the global variables in case they're called externally. With Closure in advanced mode, it seems like it can rename the global variables, however I'm having problem with the dead code removal. Most functions appear to be dead since they depend on DOM interaction and event handling and aren't called directly.
So any idea on how to minify these global variables? Do I need to just write a script to do some regex replacement? I'm also open to refactoring my code if that would fit the minification pattern better (for example, adding to a closure or whatnot)
回答1:
Minifiers won't munge public/global names since, for many scripts, that will destroy the availability and predictability of the public API.
Since you don't need to maintain a public API, making them "private" by wrapping them in a closure function may be enough:
(function () {
function myfunc1 () { ... jquery.bind('click', myfunc2) ... }
function myfunc2 () { ...
...
})();
But, even then, no guarantees as it's very much at the discretion of the minifier's authors.
回答2:
See the Semantic Designs JavaScript Obfuscator. Gives you complete control over what symbols are obfuscated, and which are not, precisely so you can manage situations like this. No need to change your working code.
I work for them.
回答3:
Please see the on-line docs for the Closure Compiler.
In other words:
- "Export" the functions you want to keep
- Make an "externs" file with functions you don't want renamed
- Run Closure Compiler in Advanced Mode
回答4:
You could make local references to commonly used jQuery functions in your code, which would then be minified?
For example:
$(function() {
var jQueryAnimate = $.animate,
jQueryAddClass = $.addClass;
$('.foo').jQueryAddClass('.bar');
});
来源:https://stackoverflow.com/questions/5698473/javascript-how-to-minfy-obfuscate-global-function-names