zoukankan      html  css  js  c++  java
  • 函数内巧用注释实现多行文本拼接

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

    常规做法:

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

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

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

    实现方案:

    function multiline(fn){
            var reCommentContents = //*!?(?:@preserve)?[ 	]*(?:
    |
    )([sS]*?)(?:
    |
    )[ 	]**//;
        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

  • 相关阅读:
    斯特林数及斯特林反演
    关于斯特林数的应用总结
    向量运算与几何意义
    linux shell——md5sum,sha1sum,sort,uniq (转)
    hudson配置教程
    linux下安装tomcat和部署web应用
    Tomcat Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
    《Ant权威指南》笔记(一)
    ant调用shell命令(Ubuntu)
    hudson--ant编写记录
  • 原文地址:https://www.cnblogs.com/blog-leo/p/5545121.html
Copyright © 2011-2022 走看看