Less 是一门 CSS 预处理语言,它扩展了 CSS 语言,增加了变量、Mixin、函数等特性,使 CSS 更易维护和扩展.
在创建项目的时候指定预编译器
在Angular/cli 7.3.8 版本创建一个项目时,Angular/cli 工具提供了多个预编译器来选,这个时候就可以指定为Less就可以了
wujiayudeMBP:~ wjy$ ng version
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 7.3.8
Node: 8.16.0
OS: darwin x64
Angular:
...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.13.8
@angular-devkit/core 7.3.8
@angular-devkit/schematics 7.3.8
@schematics/angular 7.3.8
@schematics/update 0.13.8
rxjs 6.3.3
typescript 3.2.4
wujiayudeMBP:~ wjy$ ng new demo
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? (Use arrow keys)
❯ CSS
SCSS [ http://sass-lang.com/documentation/file.SASS_REFERENCE.html#syntax ]
Sass [ http://sass-lang.com/documentation/file.INDENTED_SYNTAX.html ]
Less [ http://lesscss.org ]
Stylus [ http://stylus-lang.com
将已经有的项目将预编译器改成 Less
Angular/cli 默认的预编译器时CSS,将编译器改成 Less步骤如下:
1. 修改angular-cli.json里面的 schematics
在schematics对象中添加如下
"@schematics/angular:component": {
"style": "less"
}
修改之后如下:
"schematics": {
"@schematics/angular:component": {
"style": "less"
}
},
保存angular-cli.json 文件以后使用命令
ng g c componentName
生成的组件的样式文件就是less的了
修改前生成一个组件
wujiayudeMBP:demo wjy$ ng g c demo2
CREATE src/app/demo2/demo2.component.css (0 bytes)
CREATE src/app/demo2/demo2.component.html (20 bytes)
CREATE src/app/demo2/demo2.component.spec.ts (621 bytes)
CREATE src/app/demo2/demo2.component.ts (265 bytes)
UPDATE src/app/app.module.ts (701 bytes)
修改后生成一个组件
wujiayudeMBP:demo wjy$ ng g c demo3
CREATE src/app/demo3/demo3.component.less (0 bytes)
CREATE src/app/demo3/demo3.component.html (20 bytes)
CREATE src/app/demo3/demo3.component.spec.ts (621 bytes)
CREATE src/app/demo3/demo3.component.ts (266 bytes)
UPDATE src/app/app.module.ts (779 bytes)
2. 修改angular-cli.json里面的 styles.css 后缀改成 .less
为了不留下技术债,最好将test对象中的styles.css 后缀也改成 .less
3. 将src目录下面 style.css 改成 style.less
修改这个文件:
修改后:
4. 修改已经有组件的样式文件
-
- 将每个组件中的 componentName.component.css改成componentName.component.less
例如:将组件demo2的 demo2.component.css 改为demo2.component.less
-
- 修改类文件的元数据
将这里 styleUrls中的 './demo2.component.css' 改成'./demo2.component.less'
全部更改完以后,执行
npm run start
或者
ng serve
就可以看到效果了。