在我的 View 脚本中,我使用 View 助手添加 javascript inlineScript
并在我的模板的页脚中回应它。我现在正尝试使用 this solution 缩小生成的 html .
我的问题是我在整个代码中包含内联注释(例如 //this is a comment
)(因为我是一个优秀的开发人员),这导致所有代码都被视为注释很好(因为所有新行都被删除,并且以下代码与内联注释放在同一行)。
如何扩展 inlineScript
以删除注释和/或使用例如 mrclay minify 缩小代码?
我试过的是:
<?php echo preg_replace('#//.*#', '', $this->inlineScript()) ?>
这会导致我有代码的页面出现问题,例如:
jQuery(el).attr('data-toggle', 'popover')
.attr('data-trigger', 'hover')
.attr('data-html', 'true')
.attr('data-content', [
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="',
'//' + location.hostname + '/img/broker-logo/' + el.value,
'"/>'
].join(''))
并且,上述的变体,
<?php echo preg_replace('#[\s\t]+//.*#', '', $this->inlineScript()) ?>
它检查之前没有任何内容的评论。这引发了我在代码后跟行末注释的问题:
var $el = jQuery('table.hover') //only apply effect to hover tables
这会产生与原始问题相同的不良结果。
最佳答案
您可以添加 https://github.com/mrclay/jsmin-php删除评论和空格(请参阅问题 https://github.com/mrclay/minify/issues/581 关于评论)。
如果您正在使用 composer 项目,您可以通过以下方式将 jsmin-php
添加到您的项目中:
第一步:在 composer.json
所在的终端中运行 composer require mrclay/jsmin-php
以安装包。
2 步:将带有 JSMin::minify
的行添加到您的脚本缩小功能的实现中,这将删除评论:
function removeComments(string $code) {
// $code is variable that contains JS with comments, could be something like
// $code = 'var someCode = "blah-blah";/**comment*/';
$minifiedJs = JSMin::minify($code);
return $minifiedJs;
}
3 步:不要忘记在 .php 文件顶部添加 use JSMin\JSMin;
语句。
在您的情况下,如果 inlineScript() 真的为您返回字符串,您将像 removeComments($this->inlineScript())
那样调用它。需要注意的是,通常 inlineScript
辅助方法应该这样调用
$jsCodeWithoutComments = removeComments($jsCodeWithComments);
$this->inlineScript()->appendScript($jsCodeWithoutComments);
参见 Append Javascript File to the end of the InlineScript Collection from child view
就是这样。
关于javascript - 缩小内联脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50507016/