Laravel HTML Minify 项目教程
1. 项目的目录结构及介绍
Laravel HTML Minify 项目的目录结构如下:
laravel-html-minify/
├── app/
│ ├── Http/
│ │ ├── Middleware/
│ │ │ └── MinifyResponse.php
├── config/
│ └── htmlmin.php
├── resources/
│ ├── views/
├── routes/
│ ├── web.php
├── .gitignore
├── composer.json
├── LICENSE
├── README.md
目录介绍
- app/Http/Middleware/: 包含用于压缩 HTML 响应的中间件。
- config/: 包含项目的配置文件
htmlmin.php
。 - resources/views/: 存放 Blade 视图文件。
- routes/web.php: 定义 Web 路由。
- .gitignore: Git 忽略文件列表。
- composer.json: Composer 依赖管理文件。
- LICENSE: 项目许可证。
- README.md: 项目说明文档。
2. 项目的启动文件介绍
Laravel HTML Minify 项目的启动文件主要包括 app/Http/Middleware/MinifyResponse.php
和 routes/web.php
。
MinifyResponse.php
MinifyResponse.php
文件位于 app/Http/Middleware/
目录下,主要负责在响应发送到客户端之前压缩 HTML 内容。
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Response;
class MinifyResponse
{
public function handle(Request $request, Closure $next)
{
$response = $next($request);
if ($this->shouldMinify($response)) {
$content = $response->getContent();
$minifiedContent = $this->minifyHtml($content);
$response->setContent($minifiedContent);
}
return $response;
}
protected function shouldMinify($response)
{
return $response->headers->has('Content-Type') &&
strpos($response->headers->get('Content-Type'), 'text/html') !== false;
}
protected function minifyHtml($content)
{
// 实现 HTML 压缩逻辑
return preg_replace(['/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s'], ['>', '<', '\\1'], $content);
}
}
web.php
web.php
文件位于 routes/
目录下,定义了 Web 路由,并应用了 MinifyResponse
中间件。
use Illuminate\Support\Facades\Route;
use App\Http\Middleware\MinifyResponse;
Route::middleware(MinifyResponse::class)->group(function () {
Route::get('/', function () {
return view('welcome');
});
});
3. 项目的配置文件介绍
Laravel HTML Minify 项目的配置文件为 config/htmlmin.php
。
htmlmin.php
htmlmin.php
文件位于 config/
目录下,包含了项目的配置选项。
return [
'enabled' => env('HTML_MIN_ENABLED', true),
'blade' => [
'enabled' => env('HTML_MIN_BLADE_ENABLED', true),
],
'ignore' => [
'paths' => [],
'views' => [],
],
];
配置项介绍
- enabled: 是否启用 HTML 压缩功能,默认开启。
- blade.enabled: 是否在 Blade 视图编译时启用 HTML 压缩,默认开启。
- ignore.paths: 忽略压缩的路径列表。
- ignore.views: 忽略压缩的视图列表。
通过这些配置项,可以灵活地控制 HTML 压缩的行为。