函数内巧用注释实现多行文本拼接

经常会遇到这么个场景,需要将html代码转为JavaScript输出。
一般的做法,就是使用字符串拼接或者使用数组拼接后最终转为字符串。

常规做法:

var str = '' +
'<!doctype html>' +
'<html>' +
'   <body>' +
'       <h1>函数内巧用注释实现多行文本拼接</h1>' +
'   </body>' +
'</html>' +
'';

以前,我一般是用转换工具实现,比如这个网址:HTML to JavaScript Convertor

用工具确实是个好方法,那有没有更好的解决方案?以前曾用过函数内用注射来实现本地调试的效果,那么注释是否也可以实现字符串拼接?

实现方案:

function multiline(fn){
        var reCommentContents = /\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)[ \t]*\*\//;
    var match = reCommentContents.exec(fn.toString());
 
    if (!match) {
        throw new TypeError('Multiline comment missing.');
    }
 
    return match[1];
}

原理非常简单:

  1. 在一个function中写上一段多行注释
  2. 将此function toString()
  3. 将多行注释内容用正则匹配出来

如何使用:

multiline(function(){/*
<!doctype html>
<html>
    <body>
        <h1>函数内巧用注释实现多行文本拼接</h1>
    </body>
</html>
*/});

函数执行后的输出结果:

<!doctype html>
<html>
    <body>
        <h1>函数内巧用注释实现多行文本拼接</h1>
    </body>
</html>

利用注射巧妙的省去了字符串拼接的烦恼,那么在实际项目中是否可用?
一般在实际项目上线前,js都需要压缩,而压缩后将导致正则提取失败。

如何防止注释被压缩工具去掉?

  1. uglify: 使用 /@preserve 代替 / 即可
  2. Closure Compiler(Google): 使用 /@preserve 代替 /
  3. YUI Compressor: 使用 /! 代替 /

如果需要压缩的话,可用如下方式输出:

multiline(function(){/*!@preserve
<!doctype html>
<html>
    <body>
        <h1>函数内巧用注释实现多行文本拼接</h1>
    </body>
</html>
*/});

项目地址:https://github.com/baofen14787/multiline

posted @ 2016-05-31 10:50  Mr.Leo  阅读(441)  评论(0编辑  收藏  举报