缩小对象属性的解决方案?

Chr*_*phe 13 javascript object minify

在我的JavaScript应用程序中,我仅将几个对象用于内部目的(用户不需要访问它们).例如:

var images={
    blank:"blank.gif",
    plus:"plus.gif",
    minus:"minus.gif"
}
Run Code Online (Sandbox Code Playgroud)

当我使用像Uglify.js这样的缩小器时,属性名称(空白,加号,减号)保持不变.有没有办法缩小它们?

到目前为止我所考虑的事情:

  • 在高级模式下使用Google Closure minifier,但这会破坏我的代码
  • 用变量替换对象属性(例如var imagesBlank ="blank.gif")但它使代码的可读性降低

有没有更好的办法?

Ken*_*Lin 7

如果您为内部属性添加唯一前缀,则可以--mangle-props regexhttps://github.com/mishoo/UglifyJS2尝试。

这是它在我的 gulpfile 中的使用,它需要 gulp-uglify。

var uglifyOpts = {
    // Mangles the private "p1_" prefixed properties in an object
    mangleProperties: {
        regex: /^p1_/
    }
};
Run Code Online (Sandbox Code Playgroud)


Was*_*moo 5

使用对象允许使用变量作为属性.将它包装在一个闭包中使这些变量值得缩小.

//Wrap in closure
(function() {

    //Property Variables
    var blank = 0;
    var plus  = 1;
    var minus = 2;

    //Define Object
    var image = [];
    image[blank] = "blank.gif";
    image[plus]  = "plus.gif";
    image[minus] = "minus.gif";

    //Accessors - must be within closure
    image[blank]; //blank.gif
    image[plus];  //plus.gif
    image[minus]; //minus.gif

})();
Run Code Online (Sandbox Code Playgroud)

要访问上面的值,必须在闭包内使用常量.

如果使用谷歌的关闭编译器,使用var image = [];将在声明数组因为属性值从零编号更有效,即0,1,2.

否则,var image = {};效果也不错.


Nie*_*sol -4

好吧,在这种情况下,您可以将所有引用替换为images.blank"blank.gif"同样替换为plusminus。虽然如果您出于某种原因决定更改所有文件名,这确实意味着需要做更多的工作,但没有什么是全局搜索和替换无法解决的。images根本不需要该对象。