缩小HTML,但不要使用Gulp触及PHP

man*_*niL 8 html javascript php minify gulp

问题

我有很多.php文件,大多数都包含HTML,但顶部还有一些PHP行(例如表单触发器代码或类似代码).所以他们看起来像

<?php
if($someValue){
    //doSth
}
//more content
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <title>My Website</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
<!-- Content and scripts here -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

目标

我的目标是缩小 HTML(甚至可能是内联的javascript,但这只是额外的一点),而不是触及顶部的PHP.我正在使用Gulp作为自动构建工具,并且希望看到使用此工具的解决方案以及任何需要的额外软件包.

How*_*vis 10

一饮而尽,htmlmin模块使用HTML的minifier模块,它有大量的选项(在其npmjs.com和github上两页显示),可以使用.我们将关注的选项是ignoreCustomFragments.

var gulp = require(gulp),
    htmlmin = require(gulp-htmlmin);

gulp.task('htmltask', function(){
  return gulp.src(['./dev/*.html','./dev/*.php'])
      .pipe(htmlmin({
        collapseWhitespace: true,
        ignoreCustomFragments: [ /<%[\s\S]*?%>/, /<\?[=|php]?[\s\S]*?\?>/ ]
      }))
      .pipe(gulp.dest('./site'));
});
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,您看到我们正在使用ignoreCustomFragments正则表达式/<\?[=|php]?[\s\S]*?\?>/忽略以<?和开头的<?php结尾的代码?>.

默认情况下,html-minifier忽略php,因此您不必担心设置ignoreCustomFragments.

  • 我用这个用于我的正则表达式,允许在文件末尾的unclosed php标签`ignoreCustomFragments:[/ <\?[\ s\S]*?(?:\?> | $)/] (3认同)