假设我们有一个多行 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/