我正在使用 LESS 来组织和导入我的所有 CSS 文件。我还使用 Twitter Bootstrap,将其集成到 style.less 中。它工作得很好,如下所示,但是当我使用 lessc 来缩小 less 文件并将其压缩为一个时,我的 twitter bootstrap css 就彻底崩溃了。原因是我的
bootstrap.min.css
的图像相对路径为 "../img"
,因此当我缩小所有这些文件并转储输出文件时,它不再找到该路径。
我到底应该如何解决这个问题,我不想在我的 CSS 中硬编码绝对网址?
style.less
@import './folder_one/file_one';
@import './folder_one/file_two';
@import './folder_two/file_one';
@import './folder_three/file_one';
// this bootstrap css references images relatively ../img/
@import './bootstrap/bootstrap.min.css';
运行 lessc 时使用 --relative-urls 标志。
lessc --relative-urls
它的记录很少,但默认情况下它是 false,这意味着所有 @imported 文件将保持其原样的 url(例如背景图像、字体等)。这是因为较少的人已经这样做了,并且许多用户希望它不要打扰他们的网址。
当使用relative-urls标志时,lessc会根据导入的less/css文件的位置重写所有url。
示例
/dir1/style/main.less
// if you don't include (less) lessc will leave bootstrap
// as an @import at the top of the lessified css file
@import (less) '../bootstrap/bootstrap.min.css';
/dir1/lib/bootstrap/bootstrap.min.css
background-image:url("../img/bs-img.gif");
结果:
/dir1/style/main.css
background-image:url("../bootstrap/img/bs-img.gif");
查看文档以了解命令行用法。 https://github.com/cloudhead/less.js/wiki/Command-Line-Usage。有一个名为
--root-path
的选项,它将在现有的 url 前面添加,以便它们可以在输出 css 文件中工作。
lessc [option option=parameter ...] <source> [destination]
lessc -rp=will/be/prepended sourcefile.less path/to/destination
例如:
这是原始网址,文件位于 css/src/nest 中
background-image: url('../../../imgs/bg.png');
这就是我在命令行上要做的事情。请注意,
-rp
参数应指向从输出目录到原始文件位置
lessc -rp=src/nest css/src/nest/nesty.less css/nesty.less
以及输出,文件位于 css/
background-image:url('src/nest/../../../imgs/bg.png')
有一个
--relative-urls
选项,但我无法让它工作。我正在使用上面描述的解决方法构建脚本。 Build-o-Matic
这就是我处理确定路径的方式[链接]
--relative-urls
标志有其在浏览器内的对应标志。
<script>
less = {
env: "development",
relativeUrls: true
};
</script>
<script src="less.min.js"></script>
刚到这里,因为我也遇到了在 less 文件中解析图像 uri 的问题。
“--relative-urls”为我指明了正确的方向。
对于也到达这里的其他人: 这个参数已被弃用,你现在可以使用“--rewrite-urls”和“off”,“all”或“local” - 详细描述在这里