总结下之前做过的seajs项目,在不用构建工具情况下,单纯用了php做合并js模块做输出。类似 http://www.XXX.com/min/f=ui/page/hall/applib/detailInfo.js,直接请求 min目录下的 index.php ,然后php将全部require 的js 一起压缩输出,代码如下
<?php
header('Content-Type:application/x-javascript');
header('Cache-Control:max-age=1800');
date_default_timezone_set('UTC');
$time = date('D, d M Y H:i:s', time() + 1800) . ' GMT';
header("Expires: $time");
define("BD","/data1/XXX/script/");
$file = $_GET['f'];
if(strpos(realpath(BD.$file),realpath(BD)) === false)
{
echo 'you can not read parent directory.';
exit;
}
$buf = '';
$filemap = array();
function fetchfile($path)
{
global $filemap;
if(!file_exists($path))
{
echo 'file'.$path.'is not exist';
return;
}
if(isset($filemap[$path]))
{
return;
}
$filemap[$path] = true;
$matches = array();
$filestr = file_get_contents($path);
global $buf;
if($filestr)
{
$buf .= $filestr;
}
else
{
return;
}
preg_match_all("/require\([^\(\)]*\)/",file_get_contents($path),$matches);
for($i = 0;$i < count($matches[0]);$i++)
{
$p = '';
if(strpos($matches[0][$i],"'") !== false)
{
$p = explode("'",$matches[0][$i]);
$p = BD.$p[1];
}
else if(strpos($matches[0][$i],'"') !== false)
{
$p = explode('"',$matches[0][$i]);
$p = BD.$p[1];
}
if($p !== '')
{
if(strpos($p,'.js') !== false)
{
fetchfile($p);
}
else
{
fetchfile($p.'.js');
}
}
}
}
function ob_gzip($content)
{
if( !headers_sent() && extension_loaded("zlib") && strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip") && $content != '')
{
extension_loaded("zlib");
$content = gzencode($content);
header("Content-Encoding: gzip");
header("Vary: Accept-Encoding");
header("Content-Length: ".strlen($content));
}
return $content;
}
fetchfile(BD.$file);
$buf = ob_gzip($buf);
echo $buf;
?>
本文由 前端技术精髓 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Dec 31, 2019 at 10:12 am