Javascript优化:什么工具可以压缩顺序字符串连接?

Javascript optimization: What tool can condense sequential string concatenations?

本文关键字:顺序 压缩 字符串 连接 优化 什么 工具 Javascript      更新时间:2023-09-26

这是一个简化的例子,但是我正在开发一个输出javascript的代码翻译器。由于解析的完成方式,我必须将翻译分成几部分输出。例如,我最终得到一个javascript文件,看起来类似于以下内容,但要长得多:

function coolfunc() {
    var result = "";
    greet = function(user,town) {
        var output = '';
        output += 'Welcome ' + user + '!';
        output += 'How is the weather in ' + town + '?';
        return output;
    }
    goobye = function(user,town) {
        var output = '';
        output += 'Farewell ' + user + '!';
        output += 'Enjoy the weather in ' + town + '!';
        return output;
    }
    result += "Some output 1";
    result += "Some output 2";
    result += greet("Larry","Cool town");
    result += goobye("Larry","Cool town");
    return result;
}

是否有后处理程序可以将上面的内容压缩成如下内容:

function coolfunc() {
    greet = function(user,town) {
        var output = 'Welcome ' + user + '!'+'How is the weather in ' + town + '?';
        return output;
    }
    goobye = function(user,town) {
        var output = 'Farewell ' + user + '!'+'Enjoy the weather in ' + town + '!';
        return output;
    }
    var result = "Some output 1"+"Some output 2"+greet("Larry","Cool town")+goobye("Larry","Cool town");
    return result;
}

如果它能将相邻的静态字符串连接在一起,那就很简单了。

我认为yuiccompressor或闭包编译器会这样做,但据我所知它们没有。


编辑:

到目前为止,评论似乎告诉我在翻译中这样做。我不认为这是最好的选择,因为它会使阅读翻译变得非常困难……类似于为什么人们写冗长的代码,然后在生产环境中将其最小化。

如果有人遇到这个,看起来闭包编译器可以处理这个版本1576 (http://code.google.com/p/closure-compiler/source/detail?r=1576)