如何换用Less
新建项目
对于新建项目而言,在初始化项目时添加--style less即可
ng new [projectName] --style less
修改现有项目
第一步:将*.css文件以及引用处的后缀名改为.less;
第二步:在angular.json文件的schematics中添加如下配置
"schematics": { "@schematics/angular:component": { "styleext": "less" } },
依赖Less / Scss优略
优点
- Scss可编程能力比较强,支持函数,列表,对象,判断,循环等;
- 支持跨浏览器兼容性;
- 使用变量,可以更快地实现维护;
- 支持一系列运算符,使编码更快,更省时;
- 使用 @import 规则,这样我们就可以轻松地处理外部文件;
- Less 是用 JavaScript 编写的,它可以比 CSS 的其他预处理器更快地编译;
变量(Variables)
@nice-blue: #5B83AD; @light-blue: @nice-blue + #111; #header { color: @light-blue; }
混合(Mixins)
.bordered { border-top: dotted 1px black; border-bottom: solid 2px black; } #menu a { color: #111; .bordered; } .post a { color: red; .bordered; }
嵌套(Nesting)
#header { color: black; } #header .navigation { font-size: 12px; } #header .logo { width: 300px; } ==》 #header { color: black; .navigation { font-size: 12px; } .logo { width: 300px; } }
运算(Operations)
// example with variables @base: 5%; @filler: @base * 2; // result is 10% @other: @base + @filler; // result is 15%
函数(Functions)
@base: #f04615; @width: 0.5; .class { width: percentage(@width); // returns `50%` color: saturate(@base, 5%); background-color: spin(lighten(@base, 25%), 8); }
作用域(Scope)
@var: red; #page { @var: white; #header { color: @var; // white } }
导入(Importing)
@import "library"; // library.less @import "typo.css";
缺点
- 基于 Less 开发类库会复杂得多,实现的代码会比较脏,能实现的功能也会受到 DSL 的制约;
- Sass语义明晰但是代码很容易显得累赘;
- Less的mixin的参数如果遇到多参数和列表参数值的时候容易混淆;
- Less编程能力弱,不直接支持对象,循环,判断等,只有when判断。
PS: Less 文件需要引用的时候要“@import (reference) "../../.”,否则的话编译结果会巨大。同样的内容会被重复编译进最终的结果中。