簡體   English   中英

如何防止 JS 縮小刪除命名函數表達式的名稱?

[英]How to prevent JS minification from removing names of named-function-expressions?

我在需要跟蹤的對象上有這個函數,以及調用的父調用者和傳遞給調用者的參數。

這很好,直到縮小:

var foo = {
    FunctionToBeLogged: function GiveMeAName() {
        console.log('> %s called from %s - args: %o',
                    arguments.callee.name,
                    arguments.callee.caller.name,
                    arguments.callee.caller.arguments);
  }
}

var bar = {
  A: function A(something) {
    foo.FunctionToBeLogged('nothing', 12, true);
  },  
  B: function B(whatever, doesntMatter) {
    foo.FunctionToBeLogged('nothing', 12, true);
  }
}

bar.A(1.2, 'Fred', { });    // > GiveMeAName called from A - args: [1.2, "Fred", Object]
bar.B('Barney', 42, false); // > GiveMeAName called from B - args: ["Barney", 42, false]

縮小去掉了這些名字,我的輸出變成了:

bar.A(1.2, 'Fred', { });    // >  called from  - args: [1.2, "Fred", Object]
bar.B('Barney', 42, false); // >  called from  - args: ["Barney", 42, false]

我真的不想去創建函數聲明和賦值,因為我有很多(我用 7,564 繼承了這段代碼......我可以輕松地運行一些正則表達式來命名函數表達式。)

我該怎么做才能防止縮小器擺脫我的這些函數名稱?

為了實現這一點,你可以傳遞特定的名稱不被破壞,例如在 UglifyJS 中:

為避免這種情況,您可以使用 --reserved-file 傳遞一個文件名,該文件名應包含要從 mangling 中排除的名稱

在該文件中,您將擁有一個不想更改的名稱列表,如下所示:

{
  "vars": [ "define", "require", ... ],
  "props": [ "length", "prototype", ... ]
}

Uglify Mangle 選項文檔...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM