[英]Uglify mangles ES6 function but not the same one in ES5
實際上,我正在使用NUglify ,但我不知道這在這里是否重要。
我最近將我的代碼庫從 ES5 移到了 ES6 (ES2015),我在代碼上遇到了這樣的錯誤 jQuery 插件:
(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
是一個在其他地方定義的例程,像這樣,一個頂級 function:
funtion offsetTopRelativeTo(fromElement, toElement)
{...}
這里沒有使用 ES6 代碼結構,轉譯為 ES5與ES6 相同。
當 ES5 版本通過 NUglify 時,它產生
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);
請注意,保留了offsetTopRelativeTo
。 但是,當完全相同的ES6 版本被丑化時,它會將 function 名稱破壞為類似n
的名稱。
這破壞了我的代碼,因為完全在這個文件之外的其他例程也調用了 function,它不存在,因為它被破壞了。
為什么會這樣?
(我知道我可以用PreserveFunctionNames
調用 Nuglify 並強制它不要破壞名稱,但現在我只是想了解為什么會發生這種情況,因為代碼在 ES5 和 ES6 之間完全相同。)
我明白這是怎么回事了。 上面的示例沒有捕獲更大的上下文,即上面的代碼被包裹在一個條件中:
if (typeof jQuery != 'undefined')
{
...all of the above code...
}
看起來 NUglify 正在檢測文件是 ES6 並且還應用了不同的規則:如果 function 嵌套在條件中,則可以安全地破壞它。
這似乎是一個危險的假設,但在我的情況下,該方法可能不應該是該條件的本地方法,如果我確實想在其他地方使用它,那么我將把它移到外面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.