2

I am writing an app in .net mvc 4. I started using the .net bundling, but encountered some problems with the minification. Because the names of the variables are shortened to one letter, there was some clushes with variables being named the same (from different scripts), producing all kind of annoying bugs and errors. Is it a known problem, or am I missing somethig? Is there a way to allow minifing the script (white spaces and stuf) without variables name changes? Thank you!

dor.elmaliach
  • 515
  • 5
  • 14
  • possible duplicate of [System.Web.Optimization making function argument names stay the same for certain functions](http://stackoverflow.com/questions/13032721/system-web-optimization-making-function-argument-names-stay-the-same-for-certain) – Fals Jul 29 '14 at 18:13
  • It is a possible answer, but i don't want to implement my own minifier. akatakritos answer is more what i needed. Thanks! – dor.elmaliach Jul 29 '14 at 20:20

1 Answers1

6

You are missing something.

You really should isolate your script from the other scripts on the page. The general pattern is to wrap your code in an immediately-invoked function:

(function() {

   var person = { /* whatever */ };

})(); // <- notice the () invocation

Inside this function, all your variables (as long as they are declared with the var keyword) are scoped to the function and won't clobber externally declared variables (even after being minfied, as in your situation). The minifier is free to munge all references to person to a shorter variable name because those references are strictly contained within the anonymous function.

Of course, if you need to export a global variable for other scripts to use, then by all means be explicit about it:

(function() {

     //aLocalPerson exists only within this function
     var aLocalPerson = {};

     //aGlobalPerson can be accessed in other scripts because it is
     //declared on the window object and is implicitly available everywhere.
     //Because its a property on the window object, no decent minifier will
     //mess with its name.
     window.aGlobalPerson = {};

})();

See also this StackOverflow question on javascript variable scope.

Community
  • 1
  • 1
akatakritos
  • 9,836
  • 1
  • 23
  • 29
  • If you want to keep your variable name preventing from minification rename to share between scripts, you can do something like window["aGlobalPerson"] = {} – Oswaldo Jul 07 '15 at 15:15