Javascript heredoc

后端 未结 14 1576
盖世英雄少女心
盖世英雄少女心 2020-12-02 12:55

I need something like heredoc in JavaScript. Do you have any ideas for this? I need cross-browser functionality.

I found this:

heredoc = \'\\
14条回答
  •  無奈伤痛
    2020-12-02 13:28

    I feel bad writing a separate answer for merely an extension to @NateFerrero's answer, but I don't feel editing his answer is appropriate either, so please upvote @NateFerrero if this answer was useful to you.

    tl;dr—For those who wish to use block comments inside their heredoc...

    I mainly needed Javascript heredocs to store a block of CSS, e.g.

    var css = heredoc(function() {/*
        /**
         * Nuke rounded corners.
         */
        body div {
            border-top-left-radius: 0 !important;
            border-top-right-radius: 0 !important;
            border-bottom-right-radius: 0 !important;
            border-bottom-left-radius: 0 !important;
        }
    */});
    

    As you can see however, I like to comment my CSS, and unfortunately (as hinted by the syntax highlighting) the first */ ends the overall comment, breaking the heredoc.


    For this specific purpose (CSS), my workaround was to add

    .replace(/(\/\*[\s\S]*?\*) \//g, '$1/')
    

    to the chain inside @NateFerrero's heredoc; in complete form:

    function heredoc (f) {
        return f.toString().match(/\/\*\s*([\s\S]*?)\s*\*\//m)[1].replace(/(\/\*[\s\S]*?\*) \//g, '$1/');
    };
    

    and use it by adding a space between the * and / for "inner" block comments, like so:

    var css = heredoc(function() {/*
        /**
         * Nuke rounded corners.
         * /
        body div {
            border-top-left-radius: 0 !important;
            border-top-right-radius: 0 !important;
            border-bottom-right-radius: 0 !important;
            border-bottom-left-radius: 0 !important;
        }
    */});
    

    The replace simply finds /* ... * / and removes the space to make /* ... */, thereby preserving the heredoc until called.


    You can of course remove the comments altogether using

    .replace(/\/\*[\s\S]*?\* \//g, '')
    

    You can also support // comments if you add them to the chain:

    .replace(/^\s*\/\/.*$/mg, '')
    

    Also, you can do something other than the single space between * and /, like a -:

        /**
         * Nuke rounded corners.
         *-/
    

    if you just update the regex appropriately:

    .replace(/(\/\*[\s\S]*?\*)-\//g, '$1/')
                              ^
    

    Or maybe you'd like an arbitrary amount of whitespace instead of a single space?

    .replace(/(\/\*[\s\S]*?\*)\s+\//g, '$1/')
                              ^^^
    

提交回复
热议问题