5

This question seems to be more or less a duplicate of this one, but that one received no answers and is over 2 years old so I don't know what the protocol is (I tried to find out).

Anyway, I've written an ASP.NET MVC5 web app and it all works fine in debug. After publishing to the server with the Release configuration I started seeing the error "Uncaught ReferenceError: Cannot access 'n' before initialization".

After many hours of trawling through the code I think I've isolated the issue. I have this small function (it's a Knockout view model, but that's irrelevant):

eventIndexViewModel = function (params) {
    let self = this;

    // Map values from params object to properties of self
    for (const [key, value] of Object.entries(params)) {
        self['_' + key] = value;
    }

    self.eventsView = ko.observable(self._eventsView);
    self.calendarToggleButtonClass = ko.pureComputed(function () {
        return self.eventsView() === "calendar" ? "active" : "";
    });
    self.tableToggleButtonClass = ko.pureComputed(function () {
        return self.eventsView() === "table" ? "active" : "";
    });
};

After being minified and published to the server, if I view the source in the dev tools console it looks like this:

eventIndexViewModel = function(n) {
    let t = this;
    for (const [n,i] of Object.entries(n))
        t["_" + n] = i;
    t.eventsView = ko.observable(t._eventsView);
    t.calendarToggleButtonClass = ko.pureComputed(function() {
        return t.eventsView() === "calendar" ? "active" : ""
    });
    t.tableToggleButtonClass = ko.pureComputed(function() {
        return t.eventsView() === "table" ? "active" : ""
    })
}

It is overkill to map the properties for the params object in this way in this particular instance, but I have much larger view models with many more properties in the same project and I want to keep them code consistent, so go with it.

Unless I'm misunderstanding something, the minified version has renamed both the params variable and the key variable in the for statement to n, and I think that is what is causing my error. Certainly, that line with the for statement is where the error is thrown.

Am I understanding the cause of this problem correctly? If so, is it a bug in the minification process? And either way, how can I get around it?

Philip Stratford
  • 4,513
  • 4
  • 45
  • 71
  • Just came across [this question](https://stackoverflow.com/questions/53671821/duplicated-variable-name-in-minified-js-file) which is also essentially a duplicate but is also coming up on three years old with no accepted answer. However, it did put me onto the fact that if I replace `const [key, value]` with `var [key, value]` the minification changes it to `var [i,r]`, thus avoiding my variable name collision. Still, I'd be interested to know if there's a solution that doesn't involve me writing my code to accommodate the minification's bugs/quirks. – Philip Stratford Jul 26 '21 at 15:48

0 Answers0