哪些Gulp包可压缩HTML内容?含内联JSON脚本压缩及转PHP需求
Got it, let's tackle this problem. The core issue here is that gulp-htmlmin (powered by html-minifier under the hood) doesn't minify <script type="application/ld+json"> content by default—it only targets standard JavaScript script types like text/javascript. To handle JSON-LD compression, we'll add two extra tools to your Gulp workflow: gulp-cheerio (for manipulating HTML DOM elements) and jsonminify (for compressing JSON content).
Step 1: Install Required Packages
First, install the additional dependencies via npm:
npm install gulp-cheerio jsonminify --save-dev
Step 2: Update Your Gulp Task
Here's the modified Gulp task that handles both HTML/minified JS compression and JSON-LD minification, then renames files to .php:
const gulp = require('gulp'); const htmlmin = require('gulp-htmlmin'); const rename = require('gulp-rename'); const cheerio = require('gulp-cheerio'); const jsonminify = require('jsonminify'); gulp.task('process-html', function() { return gulp.src('src/*.html') // First: Minify JSON-LD script content .pipe(cheerio(function($, file) { // Target all application/ld+json script tags $('script[type="application/ld+json"]').each(function() { const $scriptElement = $(this); const rawJson = $scriptElement.html(); try { // Compress the JSON (removes whitespace, comments, etc.) const minifiedJson = jsonminify(rawJson); // Replace the original content with the minified version $scriptElement.html(minifiedJson); } catch (error) { console.error(`Failed to minify JSON-LD in ${file.path}:`, error); } }); }, { // Keep HTML mode (not XML) to preserve original markup structure xmlMode: false })) // Then: Compress the entire HTML + standard inline JS/CSS .pipe(htmlmin({ collapseWhitespace: true, minifyCSS: true, minifyJS: true, removeComments: true, // Add any other htmlmin options you need here })) // Rename output files to .php .pipe(rename({ extname: '.php' })) .pipe(gulp.dest('dist')); });
How This Works
- Cheerio Integration:
gulp-cheerioparses your HTML into a manipulable DOM structure, letting us target exactly the JSON-LD script tags we need. - JSON Compression:
jsonminifytakes the raw JSON content from each script tag, strips unnecessary whitespace and comments, and outputs a compact valid JSON string. - Standard HTML Minification: After fixing the JSON-LD content, we run
gulp-htmlminas usual to compress the rest of the HTML, including standard inline JavaScript and CSS. - Rename & Output: Finally,
gulp-renameconverts the files to.phpformat before saving to your destination folder.
Why Your Original Setup Didn't Work
html-minifier (the library behind gulp-htmlmin) only applies JavaScript minification to scripts with types like text/javascript, application/javascript, or no type specified. Since application/ld+json is treated as plain text, it skips compression for those tags—hence the need for the custom DOM manipulation step.
内容的提问来源于stack exchange,提问作者Meek

