在Angular 2组件中包含SASS变量

Tim*_*lix 5 javascript sass angular

我想知道我是否可以在Angular 2组件中使用sass变量.就像是:

@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;
    }
  `]

})
Run Code Online (Sandbox Code Playgroud)

我的文件_variables.scss:

$test-color: green !default;
Run Code Online (Sandbox Code Playgroud)

似乎无论我尝试什么sass变量都无法识别.任何帮助非常感谢.

T04*_*435 11

我不同意这里的正确答案是为什么.

ATM正确答案建议在需要变量的每个组件文件夹上创建_variables.scss.除非你有一个单独的组件,否则在任何规模的项目中都很难维护,在这种情况下你不需要导入; 只需使用component.scss

.angular-cli.json(Angular 6中的angular.json)中有一个选项,它打算解决这个确切的问题,这里是:

...
,
"stylePreprocessorOptions": {
  "includePaths": [
    "./scss/base"  // BASE SCSS LOCATION
  ]
},
...
Run Code Online (Sandbox Code Playgroud)

基本scss位置相对路径到该位置的当前文件(.angular-cli.json)可以添加_variables.scss _mixins.scss _anyother.scss

然后在任何component.scss中你可以:

@import 'variables';
Run Code Online (Sandbox Code Playgroud)

谢谢你的时间.

额外:根据您的示例,您似乎没有使用angular/cli来生成组件,如果是这种情况,请使用此ng gc组件名称 - 此处.


Ale*_*jin 5

包括来自单独文件的样式。

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

_variables.scss文件添加到组件的文件夹中并将其导入questions.component.scss

@import 'variables';

.questions-filter{
  a {
    color: $green;
  }
}
Run Code Online (Sandbox Code Playgroud)

这对我来说很有用。