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

问题描述 投票:0回答:3

问题

我有很多 .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 作为自动构建工具,并希望看到使用此工具和任何需要的额外包的解决方案。

javascript php html gulp minify
3个回答
17
投票

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

编辑 谢谢阿默斯克

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

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


0
投票

您可以使用此 VSCode 扩展:Minify HTML in PHP


-1
投票

这对我有用!

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

;
© www.soinside.com 2019 - 2024. All rights reserved.