我觉得仅仅为@NateFerrero's answer 的扩展写一个单独的答案很糟糕,但我觉得编辑他的答案也不合适,所以如果这个答案对你有用,请点赞@NateFerrero。
tl;dr——对于那些希望在 inside 他们的heredoc 中使用块 cmets 的人...
我主要需要 Javascript heredocs 来存储一段 CSS,例如
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;
}
*/});
然而,正如您所见,我喜欢评论我的 CSS,不幸的是(正如语法高亮所暗示的那样)第一个 */ 结束了整个评论,破坏了 heredoc。
对于这个特定目的 (CSS),我的解决方法是添加
.replace(/(\/\*[\s\S]*?\*) \//g, '$1/')
到@NateFerrero 的heredoc 内的链;完整形式:
function heredoc (f) {
return f.toString().match(/\/\*\s*([\s\S]*?)\s*\*\//m)[1].replace(/(\/\*[\s\S]*?\*) \//g, '$1/');
};
并通过在 * 和 / 之间为“内部”块 cmets 添加一个空格来使用它,如下所示:
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;
}
*/});
replace 只是找到/* ... * / 并删除空间以生成/* ... */,从而在调用之前保留heredoc。
您当然可以使用完全删除 cmets
.replace(/\/\*[\s\S]*?\* \//g, '')
你也可以支持//cmets,如果你将它们添加到链中:
.replace(/^\s*\/\/.*$/mg, '')
此外,除了* 和/ 之间的单个空格之外,您还可以执行其他操作,例如-:
/**
* Nuke rounded corners.
*-/
如果您只是适当地更新正则表达式:
.replace(/(\/\*[\s\S]*?\*)-\//g, '$1/')
^
或者您可能想要任意数量的空格而不是单个空格?
.replace(/(\/\*[\s\S]*?\*)\s+\//g, '$1/')
^^^