简体   繁体   English

在Angular 2组件中包含SASS变量

[英]Include SASS variables in an Angular 2 component

I'm wondering if i can use sass variables in an Angular 2 component. 我想知道我是否可以在Angular 2组件中使用sass变量。 Something like: 就像是:

@Component({

  selector: 'my-component',

  template: `
    <div>
      <div class="test-div">test div 1</div>
    </div>
  `,

  styles: [
    `
    @import "variables";

    .test-div{
      border: 1px solid $test-color;
    }
  `]

})

my file _variables.scss: 我的文件_variables.scss:

$test-color: green !default;

It seems whatever I try the sass variables aren't recognised. 似乎无论我尝试什么sass变量都无法识别。 Any help much appreciated. 任何帮助非常感谢。

I disagree with the correct answer here is why. 我不同意这里的正确答案是为什么。

ATM correct answer suggests creating a _variables.scss on each component folder where the variables are needed. ATM正确答案建议在需要变量的每个组件文件夹上创建_variables.scss。 This will be very to hard to maintain in any size project unless you have a single component in which case you won't need to import; 除非你有一个单独的组件,否则在任何规模的项目中都很难维护,在这种情况下你不需要导入; just use component.scss 只需使用component.scss

There is an option in .angular-cli.json(angular.json in Angular 6) , which intends to solve this exact problem, here it is: .angular-cli.json(Angular 6中的angular.json)中有一个选项,它打算解决这个确切的问题,这里是:

...
,
"stylePreprocessorOptions": {
  "includePaths": [
    "./scss/base"  // BASE SCSS LOCATION
  ]
},
...

The base scss location relative path to the current file(.angular-cli.json) in that location you can add _variables.scss _mixins.scss _anyother.scss 基本scss位置相对路径到该位置的当前文件(.angular-cli.json)可以添加_variables.scss _mixins.scss _anyother.scss

Then in any component.scss you can: 然后在任何component.scss中你可以:

@import 'variables';

Thanks for your time. 谢谢你的时间。

Extra: By your example, it seems you not using angular/cli to generate components, if that is the case use this ng gc component-name-here . 额外: 根据您的示例,您似乎没有使用angular / cli来生成组件,如果是这种情况,请使用此ng gc组件名称 - 此处

Include styles from separate file. 包含单独文件中的样式。

@Component({
  selector: 'app-questions',
  templateUrl: './questions.component.html',
  styleUrls: ['./questions.component.scss'],
})

Add _variables.scss file to component's folder and import it in questions.component.scss _variables.scss文件添加到组件的文件夹,并将其导入questions.component.scss

@import 'variables';

.questions-filter{
  a {
    color: $green;
  }
}

It works well for me. 这对我来说很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM