Is it possible to have a comment inside a es6 Template-String?

后端 未结 4 1135
攒了一身酷
攒了一身酷 2021-01-01 13:17

Let\'s say we have a multiline es6 Template-String to describe e.g. some URL params for a request:

const fields = `
    id,
    message,
    created_time,
           


        
4条回答
  •  生来不讨喜
    2021-01-01 13:46

    Option 1: Interpolation

    We can create interpolation blocks that return an empty string, and embed the comments inside them.

    const fields = `
      id,${ /* post id */'' }
      message,${ /* post status/message */'' }
      created_time,
      permalink_url,
      type
    `;
    
    console.log(fields);

    Option 2: Tagged Templates

    Using tagged templates we can clear the comments and reconstruct the strings. Here is a simple commented function that uses Array.map(), String.replace(), and a regex expression (which needs some work) to clear comments, and return the clean string:

    const commented = (strings, ...values) => {
      const pattern = /\/{2}.+$/gm; // basic idea
    
      return strings
        .map((str, i) => 
          `${str}${values[i] !== undefined ? values[i] : ''}`)
        .join('')
        .replace(pattern, '');
    };
    
    const d = 10;
    const fields = commented`
      ${d}
      id, // post ID
      ${d}
      message, // post/status message
      created_time, // ...
      permalink_uri,
      type
    `;
    
    console.log(fields);

提交回复
热议问题