javascript - 是否可以在 es6 模板字符串中进行评论?

标签 javascript ecmascript-6 backticks template-strings

假设我们有一个多行 es6 模板字符串来描述例如请求的一些 URL 参数:

const fields = `
    id,
    message,
    created_time,
    permalink_url,
    type
`;

有没有办法在反引号模板字符串中添加注释?喜欢:

const fields = `
    // post id
    id,
    // post status/message
    message,
    // .....
    created_time,
    permalink_url,
    type
`;

最佳答案

选项 1:插值

我们可以创建interpolation返回空字符串的 block ,并将注释嵌入其中。

const fields = `
  id,${ /* post id */'' }
  message,${ /* post status/message */'' }
  created_time,
  permalink_url,
  type
`;

console.log(fields);

选项 2:标记模板

使用 tagged templates我们可以清除注释并重建字符串。这是一个使用 Array.map() 的简单 commented 函数, String.replace() , 和一个正则表达式(需要一些工作)来清除评论,并返回干净的字符串:

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);

关于javascript - 是否可以在 es6 模板字符串中进行评论?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55869462/

相关文章:

javascript - 在javascript中,如何知道用户何时点击页面,或者关闭页面?

javascript - 动态从 Api 获取 token 以访问内容

javascript - 使用 Google Closure 编译器包含 Ecmascript 6 类?

node.js - 使用 socket.io 避免循环依赖

bash - 如何使用 Groovy 执行带有反引号的 shell 命令?

javascript - for 循环运行之后的语句在 for 循环完成运行之前运行

javascript - 如何 "Decompile"书签?

javascript - 如何从异步调用返回响应?

ruby - 在 Ruby 中使用反引号和管道

ruby - 如何在 Ruby 中执行 Windows CLI 命令?