简体   繁体   中英

Uglify mangles ES6 function but not the same one in ES5

I'm using NUglify , actually, but I don't know if that matters here.

I've recently moved my codebase from ES5 to ES6 (ES2015) and I'm getting errors on code like this jQuery plugin:

    (function ($)
    {
        $.fn.animateScrollIntoView = function (scrollRoot?: any)
        {
            var $scrollRoot = isSomething(scrollRoot) ? $(scrollRoot) : $('html, body');

            var offset = isSomething(scrollRoot) ?
                offsetTopRelativeTo(this, $scrollRoot) :
                this.offset().top;

            $scrollRoot.animate({
                scrollTop: offset - 25
            }, 500);

            return this;
        };
    } (jQuery));

offsetTopRelativeTo is a routine defined elsewhere like so, a top level function:

funtion offsetTopRelativeTo(fromElement, toElement)
{...}

There's no use of ES6 code constructs here, and the transpilation to ES5 is identical to ES6.

When the ES5 version goes through NUglify, it yields

    function(n)
    {
        n.fn.animateScrollIntoView = function(t)
        {
            var i = isSomething(t) ? n(t) : n("html, body"),
                r = isSomething(t) ? offsetTopRelativeTo(this, i) : this.offset().top;
            return i.animate({ scrollTop: r - 25 }, 500), this
        }
    }(jQuery);

Note that offsetTopRelativeTo is preserved. But when the exact same ES6 version is uglified, it mangles that function name to something like n .

This is breaking my code because other routines, outside of this file entirely, also call the function, which doesn't exist, because it's been mangled.

Why would this be?

(I know I can call Nuglify with PreserveFunctionNames and force it not to mangle the names, but for now I'm just trying to understand why this is happening, since the code is exactly the same between ES5 and ES6.)

I figured out what is going on here. The above sample didn't capture the larger context, which is that the above code is wrapped in a conditional:

if (typeof jQuery != 'undefined')
{
...all of the above code...
}

It appears that NUglify is detecting that the file is ES6 and also applying a different rule: if a function is nested in a conditional, it's safe to mangle it.

This seems like a dangerous assumption, but in my case the method probably shouldn't be local to that conditional, if I do in fact want to use it elsewhere, so I'll just move it outside.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM