利用 PHP 的 auto_prepend_file 機制,在每個腳本執行前自動載入合併邏輯,實現多個 JS/CSS 檔案的動態合併輸出,上線前再透過批次處理生成靜態檔案,兼顧開發便利與生產效能。
; 必須項
auto_prepend_file = "C:\xampp\htdocs\auto_prepend_file.php"
; 可選,允許包含遠端 URL
allow_url_include = On
auto_prepend_file.php<?php
/**
* 引入並合併靜態資源檔案
* @param array|string $files 相對路徑陣列或單一路徑
* @param string $path 當前執行腳本路徑 (__FILE__)
*/
function import_static($files, $path = null)
{
// 保存並切換工作目錄,解決相對路徑問題
$oldDir = getcwd();
$baseDir = $path ? dirname($path) : dirname(__FILE__);
chdir($baseDir);
// 統一轉為陣列
if (!is_array($files)) {
$files = [$files];
}
// 根據第一個檔案副檔名自動發送 Content-Type
if (isset($files[0]) && !ob_get_contents()) {
if (stripos($files[0], '.js') !== false) {
header('Content-Type: text/javascript');
} elseif (stripos($files[0], '.css') !== false) {
header('Content-Type: text/css');
}
}
// 依序引入檔案
foreach ($files as $file) {
require_once $file;
}
// 還原工作目錄
chdir($oldDir);
}
base.js.php<?php
import_static([
'a.js',
'b.js',
'../c.js',
'../moduleB/all.js.php' // 也可引用其他 PHP 合併檔
], __FILE__);
<script type="text/javascript" src="base.js.php"></script>
上線前執行以下兩步,將動態合併轉為靜態檔案:
php *.js.php > *.js(並刪除 *.js.php)preg_replace() 將 *.js.php 替換為 *.jsinclude() 相對路徑失效的痛點auto_prepend_file,改用靜態檔