Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC4 Bundle minification doesn't work with javascript reserved words

Using the latest version of MVC4 I can't minify javascript when it contains reserved words as key names!

See the error below with the valid javascript that should have been minified.

Does anyone know how to fix this short of rewriting the javascript to use [""] notation?

PS The code in question is a few thousand lines long, so it's not an option!

/* Minification failed. Returning unminified contents.
(3,9-15): run-time warning JS1010: Expected identifier: delete
(4,9-13): run-time warning JS1010: Expected identifier: case
(5,9-11): run-time warning JS1010: Expected identifier: if
(3,9-15): run-time error JS1137: 'delete' is a new reserved word and should not be used as an identifier: delete
(4,9-13): run-time error JS1137: 'case' is a new reserved word and should not be used as an identifier: case
(5,9-11): run-time error JS1137: 'if' is a new reserved word and should not be used as an identifier: if
 */
var context = {};

context.delete = {};
context.case = {};
context.if = {};

The question is without going with another option like node, cassette, combres, servicestack etc

How do we get MVC4 to play ball with reserved words.

I find it hard to believe that after 6 months plus that there is no support for this!

like image 450
James Kyburz Avatar asked Nov 16 '12 09:11

James Kyburz


1 Answers

Just tried this and it works. Sorry but the ugly code. It will replace your members named delete and the usages of them.

public class CustomBundle : ScriptBundle
{
    public CustomBundle(string virtualPath) : base(virtualPath)
    {
        this.Builder = new CustomBuilder();
    }
    public CustomBundle(string virtualPath, string cdnPath) : base(virtualPath, cdnPath) {}
}

public class CustomBuilder : IBundleBuilder {
    public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<FileInfo> files)
    {
        var content = new StringBuilder();
        foreach (var fileInfo in files)
        {
            var parser = new Microsoft.Ajax.Utilities.JSParser(Read(fileInfo));
            parser.Settings.AddRenamePair("delete", "fooDelete");
            content.Append(parser.Parse(parser.Settings).ToCode());
            content.Append(";");
        }

        return content.ToString();
    }

    private string Read(FileInfo file)
    {
        using(var r = file.OpenText())
        {
            return r.ReadToEnd();
        }
    }
}
like image 125
Daniel Avatar answered Sep 28 '22 03:09

Daniel