定制 backstage/laravel-minify-html-middleware 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

backstage/laravel-minify-html-middleware

Composer 安装命令:

composer require backstage/laravel-minify-html-middleware

包简介

This package minifies HTML responses in Laravel safely.

README 文档

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

A lightweight and efficient Laravel middleware package that automatically minifies HTML responses, reducing page size and improving load times. The package intelligently removes unnecessary whitespace, comments, and optimizes your HTML output while preserving functionality.

Features

  • Automatic HTML Minification: Minifies HTML responses on-the-fly with zero configuration required
  • Smart Detection: Only processes HTML responses, automatically skipping JSON, AJAX requests, and other non-HTML content
  • Safe Minification: Preserves content in sensitive elements like <pre>, <textarea>, and <script> tags
  • Framework-Aware: Compatible with Livewire, Knockout.js, and other JavaScript frameworks
  • Configurable Transformers: Choose which transformations to apply or create custom ones
  • Performance Optimized: Minimal overhead with efficient regex-based transformations
  • Laravel 10, 11, and 12 Support: Works seamlessly with modern Laravel versions

What Gets Minified?

The package includes three built-in transformers:

  1. Remove Comments: Strips HTML comments while preserving framework-specific comments (Livewire, Knockout.js)
  2. Remove Whitespace: Eliminates unnecessary whitespace between tags and multiple spaces
  3. Trim Scripts: Removes extra whitespace from within <script> tags

Before Minification:

<!DOCTYPE html>
<html>
    <head>
        <title>My Page</title>
        <!-- This is a comment -->
    </head>
    <body>
        <div class="container">
            <h1>   Welcome   </h1>
            <script>
                console.log('Hello World');
            </script>
        </div>
    </body>
</html>

After Minification:

<!DOCTYPE html><html><head><title>My Page</title></head><body><div class="container"><h1>Welcome</h1><script>console.log('Hello World');</script></div></body></html>

Requirements

  • PHP 8.2 or higher
  • Laravel 10.x, 11.x, or 12.x

Installation

Install the package via Composer:

composer require backstage/laravel-minify-html-middleware

The package will automatically register its service provider.

Publish Configuration

Publish the configuration file to customize the transformers:

php artisan vendor:publish --tag="laravel-minify-html-middleware-config"

This will create a config/minify-html.php file with the following default configuration:

<?php

return [
    'transformers' => [
        Backstage\MinifyHtml\Transformers\RemoveComments::class,
        Backstage\MinifyHtml\Transformers\RemoveWhitespace::class,
        Backstage\MinifyHtml\Transformers\TrimScripts::class,
    ],
];

Usage

Global Middleware

To minify all HTML responses in your application, add the middleware to the global middleware stack in bootstrap/app.php (Laravel 11+):

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Backstage\MinifyHtml\Middleware\MinifyHtml;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(MinifyHtml::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

For Laravel 10, add to app/Http/Kernel.php:

protected $middleware = [
    // ...
    \Backstage\MinifyHtml\Middleware\MinifyHtml::class,
];

Route Middleware

To apply minification to specific routes or route groups, register the middleware with an alias:

Laravel 11+ (bootstrap/app.php):

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'minify' => \Backstage\MinifyHtml\Middleware\MinifyHtml::class,
    ]);
})

Laravel 10 (app/Http/Kernel.php):

protected $middlewareAliases = [
    // ...
    'minify' => \Backstage\MinifyHtml\Middleware\MinifyHtml::class,
];

Then apply it to specific routes:

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware('minify');

// Or to a group
Route::middleware(['minify'])->group(function () {
    Route::get('/about', [AboutController::class, 'index']);
    Route::get('/contact', [ContactController::class, 'index']);
});

Conditional Minification

The middleware automatically determines if a response should be minified based on several conditions:

  • ✅ Request method is GET or HEAD
  • ✅ Response contains HTML (checks Accept header)
  • ❌ Request is JSON
  • ❌ Request is AJAX (XMLHttpRequest)
  • ❌ Request is a precognitive request
  • ❌ Response has no DOCTYPE declaration in the first 100 characters

This ensures that only actual HTML page responses are minified, avoiding issues with API responses or partial HTML fragments.

Configuration

Customizing Transformers

You can customize which transformers are applied by modifying the config/minify-html.php file:

<?php

return [
    'transformers' => [
        // Use only specific transformers
        Backstage\MinifyHtml\Transformers\RemoveComments::class,
        Backstage\MinifyHtml\Transformers\RemoveWhitespace::class,
        // Backstage\MinifyHtml\Transformers\TrimScripts::class, // Disabled

        // Add custom transformers
        App\HtmlTransformers\CustomTransformer::class,
    ],
];

Disabling Specific Transformers

Remove or comment out any transformer you don't want to use:

<?php

return [
    'transformers' => [
        // Only remove whitespace, keep comments
        Backstage\MinifyHtml\Transformers\RemoveWhitespace::class,
    ],
];

Creating Custom Transformers

You can create your own HTML transformers by implementing a simple transform method:

<?php

namespace App\HtmlTransformers;

class RemoveMetaTags
{
    public function transform(string $html): string
    {
        // Remove all meta tags
        return preg_replace('/<meta[^>]*>/i', '', $html);
    }
}

Then add it to your configuration:

<?php

return [
    'transformers' => [
        Backstage\MinifyHtml\Transformers\RemoveComments::class,
        Backstage\MinifyHtml\Transformers\RemoveWhitespace::class,
        Backstage\MinifyHtml\Transformers\TrimScripts::class,
        App\HtmlTransformers\RemoveMetaTags::class,
    ],
];

Example: Uppercase Title Transformer

<?php

namespace App\HtmlTransformers;

class UppercaseTitle
{
    public function transform(string $html): string
    {
        return preg_replace_callback(
            '/<title>(.*?)<\/title>/i',
            function ($matches) {
                return '<title>' . strtoupper($matches[1]) . '</title>';
            },
            $html
        );
    }
}

Built-in Transformers Explained

RemoveComments

Removes HTML comments while preserving special comments needed by frameworks:

// Removes: <!-- This will be removed -->
// Keeps: <!--Livewire--> and <!-- ko --> (Knockout.js)

RemoveWhitespace

Intelligently removes whitespace while preserving content in:

  • <pre> tags (preformatted text)
  • <textarea> tags (form inputs)
  • <script> tags (JavaScript code)

The transformer:

  1. Temporarily hides protected elements
  2. Removes multiple spaces, tabs, and newlines
  3. Removes spaces between tags (> < becomes ><)
  4. Restores protected elements

TrimScripts

Removes leading and trailing whitespace from within <script> tags without affecting functionality:

<!-- Before -->
<script>
    console.log('Hello');
</script>

<!-- After -->
<script>console.log('Hello');</script>

Performance Benefits

HTML minification can reduce your HTML file size by 10-30% on average, depending on your code formatting:

  • Faster Page Loads: Smaller HTML files download quicker
  • Reduced Bandwidth: Lower data transfer costs
  • Improved SEO: Faster page loads contribute to better search rankings
  • Better Mobile Experience: Crucial for users on slower connections

Example size reduction:

  • Before: 45 KB
  • After: 32 KB
  • Savings: 28.9% reduction

Framework Compatibility

Livewire

The package preserves Livewire comments and attributes, ensuring full compatibility:

<!-- Livewire components work perfectly -->
<div wire:model="name">
    <!-- Livewire comment preserved -->
</div>

Inertia.js

Works seamlessly with Inertia.js responses as they are JSON and automatically skipped.

Alpine.js

Alpine.js directives and attributes are preserved:

<div x-data="{ open: false }">
    <button @click="open = !open">Toggle</button>
</div>

Troubleshooting

HTML Not Being Minified

  1. Check your response type: Ensure the response has an Accept: text/html header
  2. Verify middleware is registered: Confirm the middleware is in your global or route middleware
  3. Check request method: Only GET and HEAD requests are processed
  4. DOCTYPE declaration: Make sure your HTML includes <!DOCTYPE html> early in the response

Broken Layout or Functionality

  1. Whitespace-dependent CSS: If your layout relies on whitespace between inline elements, add those elements to the ignoreElements array in a custom transformer
  2. Template literals in scripts: Complex JavaScript might need special handling
  3. Pre-formatted content: Ensure <pre> and <textarea> tags are being preserved

Debugging

Temporarily disable transformers one by one to identify which transformation is causing issues:

<?php

return [
    'transformers' => [
        // Backstage\MinifyHtml\Transformers\RemoveComments::class,
        Backstage\MinifyHtml\Transformers\RemoveWhitespace::class,
        // Backstage\MinifyHtml\Transformers\TrimScripts::class,
    ],
];

Testing

Run the package tests:

composer test

Run tests with coverage:

composer test-coverage

Run static analysis:

composer analyse

Fix code style:

composer format

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

backstage/laravel-minify-html-middleware 适用场景与选型建议

backstage/laravel-minify-html-middleware 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.9k 次下载、GitHub Stars 达 6, 最近一次更新时间为 2025 年 02 月 26 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「middleware」 「laravel」 「vormkracht10」 「backstage」 「minify-html」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 backstage/laravel-minify-html-middleware 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 backstage/laravel-minify-html-middleware 我们能提供哪些服务?
定制开发 / 二次开发

基于 backstage/laravel-minify-html-middleware 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.9k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 17
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 6
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-02-26