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

Minify HTML, but don't touch PHP with Gulp

本文关键字:Gulp 触摸 PHP HTML 缩小      更新时间:2023-09-26

问题

我有很多. 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模块使用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开始并以?>结束的代码。

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

编辑由于amersk

一些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'));
  });
;