本文假定 LESSPHP v0.3.8+ 不确定早期版本,但如果不是直接开箱即用,您将了解其工作原理。
<link rel="stylesheet" type="text/css" href="styles/main.less" />
如果您使用 less.js 编译客户端,请确保将 rel="stylesheet/less" 更改为 rel="stylesheet"
1) 获取Lessphp 我将这些文件放在/www/compilers/lessphp/ 中作为演示的上下文
2) 制作一个我们可以丢弃 LESS 文件的 PHP 脚本。这将处理缓存、编译为 CSS 并将 CSS 作为响应返回。我已将此文件放在/www/compilers/ 并称之为lessphp.php
大部分代码都在 Lessphp 网站上,除了其中有错误,我在最后添加了响应。
<?php
require "lessphp/lessc.inc.php";
$file = $_GET["file"];
function autoCompileLess($inputFile, $outputFile) {
// load the cache
$cacheFile = $inputFile.".cache";
if (file_exists($cacheFile)) {
$cache = unserialize(file_get_contents($cacheFile));
} else {
$cache = $inputFile;
}
$less = new lessc;
$less->setFormatter("compressed");
$newCache = $less->cachedCompile($cache);
if (!is_array($cache) || $newCache["updated"] > $cache["updated"]) {
file_put_contents($cacheFile, serialize($newCache));
file_put_contents($outputFile, $newCache['compiled']);
}
}
autoCompileLess('../' . $file, '../' . $file . '.css');
header('Content-type: text/css');
readfile('../' . $file . '.css');
?>
这会将 LESS 文件(例如,styles/main.less)编译为缓存文件和 CSS 文件(例如,styles/main.less.css)。
3) 添加mod_rewrite 规则,以便将用户请求的任何LESS 文件重定向到我们的编译器,并为其指定路径。这被放置在根 .htaccess 文件中。
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^([^.]*\.less)$ compilers/lessphp.php?file=$1 [R,QSA,L]
</ifModule>
如果您使用的是 WordPress,则需要在其后执行此规则 - 即使 WordPress 在子目录中,它似乎也会覆盖这些规则,并且对于下面存在的引用文件不会发生 LESS 编译(目录明智) WordPress 的.htaccess 规则。
4) 您的 LESS 代码应相对于编译器位置进行相对引用。此外,如果有空属性,Lessphp 编译器将失败,例如。 background-color: ;
如果一切正常,应该会出现以下情况:
直接浏览你的LESS文件http://domain.com/styles/main.less
自动重定向到http://domain.com/compilers/lessphp?file=styles/main.less
以缩小的 CSS 呈现
main.less.css 和 main.less.cache 现在应该与您的 LESS 文件存在于同一目录中
除非您更新 LESS 文件,否则最后修改日期不应更改