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

Minify HTML, but don't touch PHP with 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>

目标

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

gulp-htmlmin module uses the 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'));
});

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

默认情况下,html-minifier会忽略php,所以不用担心设置ignoreCustomFragments.

编辑 谢谢阿默斯克

您使用的一些 php 文件可能没有结束标签,例如许多 WordPress 文件没有。另一种方法是改用以下内容:

ignoreCustomFragments: [/<\?[\s\S]*?(?:\?>|$)/]

这对我有用!

// Gulp.js configuration
var

  // modules
  gulp = require('gulp'),
  newer = require('gulp-newer'),
  htmlmin = require('gulp-htmlmin')

  // development mode?
  devBuild = (process.env.NODE_ENV !== 'production'),

  // folders
  folder = {
    src: 'src/',
    build: 'build/'
  }

  gulp.task('minify', () => {
     return gulp.src('src/*.html')
     .pipe(htmlmin({ collapseWhitespace: true }))
     .pipe(gulp.dest('dist'));
  });

;