Skip to content Skip to sidebar Skip to footer

Typescript/javascript Minification

I have a web application written in TypeScript and at some point, all the output of the compiled .ts files will be minified. Now, at some point in my code I do something like this:

Solution 1:

As already stated in other answers - most JavaScript minifiers won't change names of the publicly available symbols as it may break external code.

However, some minifiers offer more aggressive compression modes that may actually rename symbols that are potentially visible to the outer scope unless you protect them using special comments or some other technics. For example take a look at the Google Closure compiler in advanced compilation mode - https://developers.google.com/closure/compiler/docs/api-tutorial3

Solution 2:

A minifier doesn't change publicly available names, it only changes names that are isoldated inside a scope so that they can't be reached from outside code. The code is supposed to be functionally equivalent after minifying.

As you see in your example the minifyer hasn't changed global variables like for example Test, but it has changed the local variable method into t.

Solution 3:

Minifiers usually won't change variable names that can be accessed outside the current closure. This could cause problems, for example, if you define your Test class in one file and outside it you try to call it using the same name Test.

So, for example, the minified version of the following code:

function myFunction() {
  var myVariable = 'hello world';
  alert(myVariable);
}

myFunction();

Will be minified to:

function myFunction(){var n="hello world";alert(n)}myFunction();

The variable myVariable was renamed to n because it can't be accessed outside the function, but myFunction continues with its name to ensure it can be accessed anywhere.

If you know this function won't be called in other places, you could place it inside a closure like this:

(function() {
  functionmyFunction() {
    var myVariable = 'hello world';
    alert(myVariable);
  }

  myFunction();
})()

// myFunction won't be accessible here

Then your code would be minified to:

!function(){functionl(){var l="hello world";alert(l)}l()}();

Post a Comment for "Typescript/javascript Minification"