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

后端 未结 4 1224
攒了一身酷
攒了一身酷 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:50

    Just don't use template strings:

    const fields = [
        'id',  // comment blah blah
        'message',
        'created_time',
        'permalink_url',
        'type'
    ].join(',');
    

    You pay the cost of the array and method call on initialization (assuming the JIT isn't smart enough to optimize it away entirely.

    As pointed out by ssube, the resulting string will not retain the linebreaks or whitespace. It depends on how important that is, you can manually add ' ' and '\n' if necessary or decide you don't really need inline comments that badly.

    UPDATE

    Note that storing programmatic data in strings is generally held to be a bad idea: store them as named vars or object properties instead. Since your comment reflects your just converting a bunch of stuff into a url query string:

    const makeQueryString = (url, data) => {
      return url + '?' + Object.keys(data)
        .map(k => `${k}=${encodeURIComponent(data[k))})
        .join('&');
    };
    
    let qs = makeQueryString(url, {
      id: 3,
      message: 'blah blah',
      // etc.
    });
    

    Now you have stuff that is easier to change, understand, reuse, and more transparent to code analysis tools (like those in your IDE of choice).

提交回复
热议问题