Angular-cli创建的项目可以选择css的预处理scss作为style文件的默认预处理格式。scss可以设置变量,函数,同时使用继承,混入等方法达到更方便,通用的效果。
通常情况下,我们会设计一些通用的变量在各个地方使用,如何将通用变量的文件一次引入,全局使用呢?
解决办法: 这个方法有问题,似乎在angular-cli7 上不起作用
// 通用变量文件 _variables.scss
$red: #e0301e;
// 全局scss文件 styles.scss
/* You can add global styles to this file, and also import other style files */
@import 'assets/scss/variables';
// angular.json 配置预处理路径和样式路径
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/angular-toolkits",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"stylePreprocessorOptions": {
"includePaths": [
"src/assets/scss"
],
"styles": [
"src/styles.scss"
],
"scripts": []
},
// 某个component使用$red变量 sde-menu-items.scss
button {
background-color: $red
}
方法二:
您只需要添加更多配置,因此在声明全局变量的地方,您需要将其包装起来:root{}
。所以src/styles/settings/_variables.scss
。
:root
{
--blue: #00b; // or any global you wish to share with components
}
然后,当您在SCSS中使用它们时,您将需要像这样访问它们。
.example-class {
background-color: var(--blue)
}
这就是我当前的项目如何处理全局变量,它似乎运作良好。这将消除在您使用的每个scss文件中导入变量的需要。