MicrosoftAjaxMinifier doesn't seem to remove "unreachable code"

108 Views Asked by At

I'm using this with BundleTransformer from nuget and System.Web.Optimisation in an ASP.Net app. According to various docs this minifier is supposed to "remove unreachable code". I know it's not as aggressive as google closure (which I can't use presently) but I can't get even the simplest cases to work, eg;

function foo() {
}

where foo isn't called from anywhere. I can appreciate the argument that says this might be an exported function but I can't see a way to differentiate that. All my JS code is concatenated so it would be able to say for sure whether that function was needed or not if I can find the right switches.

The only way I've found to omit unnecessary code is to use the debugLookupList property in the web.config for BundleTransformer but that seems like a sledgehammer to crack a nut. It's not very granular.

Does anyone have an example of how to write so-called 'unreachable code' that this minifier will recognise?

Here's a place to test online

1

There are 1 best solutions below

1
On

I doubt the minifier has any way of knowing if a globally defined function can be removed safely (as it doesn't know the full scope). On the other hand it might not remove any unused functions and might only be interested in unreachable code (i.e. code after a return).

Using the JavaScript Module Pattern, your unused private functions would most likely get hoovered up correctly (although I've not tested this). In the example below, the minifier should only be confident about removing the function called privateFunction. Whether it considers unused functions as unreachable code is another matter.

var AmazingModule = (function() {
    var module = {};

    function privateFunction() {
        // ..
    }

    module.otherFunction = function() {
        // ..
    };

    return module;
}());

function anotherFunction() {
    // ..
}