javascript - how to minfy/obfuscate global function names?

女生的网名这么多〃 提交于 2020-12-04 03:36:51

问题


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:

  1. "Export" the functions you want to keep
  2. Make an "externs" file with functions you don't want renamed
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!