Gulp-htmlmin无法识别<xmp>标签进行HTML压缩的问题
问题:Gulp-htmlmin无法压缩标签内的内容? <a class="header-anchor" href="#问题:gulp-htmlmin无法压缩标签内的内容?" aria-hidden="true">#</a></h1>
<p>我看你遇到的问题是,用gulp-htmlmin压缩HTML时,<xmp>标签里的内容完全没被处理——里面的class属性还保留着引号,换行也没去掉,但外面的标签都正常压缩了。咱们来一步步解决这个问题:</p>
<h2 id="为什么会这样?">为什么会这样? <a class="header-anchor" href="#为什么会这样?" aria-hidden="true">#</a></h2>
<p>首先得说,<xmp>是个<strong>已经被HTML5废弃的标签</strong>了,它的作用是直接展示原始HTML内容,不需要转义。而gulp-htmlmin依赖的html-minifier库,默认会把<xmp>内部的内容当作「原始文本」,不会对其进行任何压缩处理,这就是为什么里面的内容和你写的一模一样,没被修改。</p>
<h2 id="解决方案(推荐第一种,符合标准)">解决方案(推荐第一种,符合标准) <a class="header-anchor" href="#解决方案(推荐第一种,符合标准)" aria-hidden="true">#</a></h2>
<h3 id="方案1:替换为标准的组合">方案1:替换<xmp>为标准的<pre><code>组合 <a class="header-anchor" href="#方案1:替换为标准的组合" aria-hidden="true">#</a></h3>
<p>既然<xmp>已经被废弃,不如换成现在推荐的写法:用<pre><code>包裹内容,同时把内部的HTML字符转义(比如<code><</code>改成<code>&lt;</code>,<code>></code>改成<code>&gt;</code>)。这样既符合HTML规范,htmlmin也能正常压缩内部内容。</p>
<p>修改你的HTML代码:</p>
<pre class="hljs"><code class="language-html volc-pre-code"><pre><code>&lt;u>This is U tag with underlined aqua - Default &lt;/u>
&lt;u class="u-gold">This is U tag with underlined gold&lt;/u>
&lt;u class="u-orange">This is U tag with underlined orange&lt;/u></code></pre>
</code></pre>
<p>这样处理后,htmlmin会自动压缩里面的属性(比如把<code>class="u-gold"</code>变成<code>class=u-gold</code>),还能去掉多余的换行和空格。</p>
<h3 id="方案2:强制让htmlmin处理内部内容(不推荐,因为已废弃)">方案2:强制让htmlmin处理<xmp>内部内容(不推荐,因为<xmp>已废弃) <a class="header-anchor" href="#方案2:强制让htmlmin处理内部内容(不推荐,因为已废弃)" aria-hidden="true">#</a></h3>
<p>如果你一定要保留<xmp>标签,可以在gulp管道里先手动处理<xmp>内部的内容,再交给htmlmin压缩。需要用到<code>gulp-replace</code>插件:</p>
<ol>
<li>先安装gulp-replace:</li>
</ol>
<pre class="hljs"><code class="language-bash volc-pre-code">npm install gulp-replace --save-dev
</code></pre>
<ol start="2">
<li>修改你的gulpfile.js:</li>
</ol>
<pre class="hljs"><code class="language-javascript volc-pre-code">let htmlmin = require('gulp-htmlmin');
let replace = require('gulp-replace');
// ...
gulp.task('html', gulp.series('clean', function() {
return gulp.src(globs.html)
// 先处理<xmp>内部的内容
.pipe(replace(/<xmp>([\s\S]*?)<\/xmp>/g, (match, innerContent) => {
// 压缩内部:去掉多余换行和空格,移除属性引号
let minifiedInner = innerContent
.replace(/\n\s+/g, ' ') // 去掉换行和前面的空格
.replace(/\s+/g, ' ') // 合并多余空格
.replace(/(["'])([^"']+)\1/g, '$2'); // 移除属性的引号
return `<xmp>${minifiedInner}</xmp>`;
}))
.pipe(htmlmin({
collapseWhitespace: true,
removeComments: true,
}))
.pipe(gulp.dest('./dist'));
}));
</code></pre>
<p>这样处理后,<xmp>内部的内容就会被压缩,和外面的标签保持一致的压缩效果。</p>
<p>内容的提问来源于stack exchange,提问作者user11831257</p>
相关产品推荐
相关产品推荐

