昨天讲了基于r.js 的js压缩,今天来讲css得压缩。
有了js的基础,css相对就简单多了,套路都一样。
因为css不需要循环遍历依赖的过程,所以它的combine_css.php 会简单的多。
首先还是看下目录结构
和js 的目录很像吧,但是简单了很多。
/css/dist/home.dev.css 是本地加载的合并后的文件,home.css 是生产环境下加载的压缩过的css。
/css/config/home.css 是配置文件,用来配置dist下的文件由src下的哪些文件合并而成的
首先html里加载和正常加载的方式一样
<link href="/css/dist/home.css" rel="stylesheet" type="text/css" />
.htaccess 的完整代码在上一篇里有。这里就贴下css部分的
rewriteCond %{REQUEST_FILENAME} ^(.*)\.(js|css)$
rewriteCond %1.dev.%2 -f
RewriteRule ^(.*)\.(js|css)$ $1.dev.$2 [L]
然后看下combine_css.php吧
<?php
include 'notmodified.php';
define('BASE', dirname(__FILE__));
$file_main = BASE.'/../'.$_GET['f'];
$css_require_reg_exp = '/\s*@import\s*url\s*\(\s*[\"\']([^\'\"]+)[\"\']\s*\)/';
$data_dep_file = array($file_main);
if(file_exists($file_main)){
$text_main = file_get_contents($file_main);
preg_match_all($css_require_reg_exp, $text_main, $matches);
if(isset($matches[1]) && is_array($matches[1]) && count($matches[1]) > 0){
foreach($matches[1] as $v){
$v_path = BASE.'/../css/config/'.$v.(strrchr($v, '.') == '.css' ? '' : '.css');
if(!in_array($v_path, $data_dep_file)){
$data_dep_file[] = $v_path;
}
}
}
}
$ext = strrchr($file_main, '.');
$file_name = basename($file_main, $ext);
$file_output = BASE.'/../css/dist/'.$file_name.'.dev.css';
if(file_exists($file_output) && notmodified($data_dep_file)){
exit;
}
$output = array();
$error = array();
exec('node r.js -o cssIn='.$file_main.' out='.$file_output.' optimize=none', $output);
foreach($output as $v){
if(preg_match('/Error/', $v)){
$error[]=json_encode($v); //保存错误信息
}
}
if(empty($error)){
header('Content-Type: text/css');
echo file_get_contents($file_output);
exit;
}
foreach($error as $e){
echo "console.error($e);"; //输出错误信息
}
exit;
代码很简单就是通过正则去/css/config/home.css 下去提取依赖文件,用来判断是否需要合并用的
只要看下/css/config/home.css 就会都明白的。
@import url("../common.css");
@import url("../a.css");
@import url("../b.css");
通过combine_css.php 合并出来了 product/spc.dev.css 后,剩下的步骤就和js的一样了
完整代码也在前一篇有,css部分的是这样的
else if(substr($f, -8) == '.dev.css'){
$out = substr($f, 0, -8).'.css';
if(!file_exists($out) || filemtime($f) > filemtime($out)){
system('node r.js -o cssIn='.$f.' out='.$out.' optimizeCss=standard'); //r.js 压缩css的命令
}
}
这里要注意压缩css的参数就行了,和合并的有所不同
批处理的代码就不贴了,在上一篇有,一共就4行代码。
压缩好后,就是本地加载spc.dev.css,生产环境加载spc.js
到此css的压缩也结束了,比js得简单多了。
同样前面所讲的js 的小bug这里也有。只好忍着了。