[英]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模块使用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'));
});
在上面的代码中,您看到我们使用带有正则表达式/<\\?[=|php]?[\\s\\S]*?\\?>/
ignoreCustomFragments
来忽略以<?
和<?php
并以?>
结尾。
默认情况下, 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'));
});
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.