Angular SCSS Global Variable Import

随声附和 提交于 2021-01-26 19:29:24

问题


I would like to move over to SCSS in my Angular project. So far the only use I want from SCSS is the variables. At the moment I have been using CSS variables which work very nicely because you declare them in :root in my styles.css and then you can use them in all the components' CSS files in the app.

My question is whether this is possible with SCSS (a global import)? Because I find it very tedious to move from a language that imported globally by it self (CSS) to something that now requires me to import variables wherever I need it (SCSS).

I am a bit disappointed on why a better version of something would require me to do this. Therefore I am sure there must be some way to not have to import my variables in every SCSS I need them in.

For example, I want to create variables in my styles.scss, and then I want to be able to use those variables in any of my components' styles, without importing anything. In CSS variables like --MyVar in :root is accessible from any components' CSS.


回答1:


You don't need to import variables everytime consider this example

theme.scss

$primary-color:#00b289;
$secondary-color:#505050;

@import "components/_checkbox";
@import "components/_button";

as you can see I only decalre my variables once and I can use the variables inside my partial sass file.

another way is to create a partial sass file include all your variables and imported once

theme.scss

@import "_variables.scss";
@import "components/_checkbox";
@import "components/_button";



回答2:


I don't think u need to import scss variable everywhere wherever you want to use it

Suppose you have a file

_variables.scss

$white:#fff;
$black:#000;

then in main.scss u can import this file

main.scss

@import "variables.scss";

Now suppose u want to use these variables in, for eg _button.scss file

_button.scss

button{
 color:$black
}

You can directly use these variables provide that you import the _button.scss file in main.scss file after variable.scss

Placing it after varibles.scss files will ensure that the variables will be accessible in button.scss file

main.scss

@import "variables.scss";
@import "button.scss";

As for CSS variables, you are free to use them SCSS,

try running the follwing snippet in Sassmeister

:root{
  --gridWidth: 45px; 
  --gridHeight: 45px; 
}

.Grid {
    width: var(--gridWidth);
    height: var(--gridHeight);
    border: 1px solid black;
}


来源:https://stackoverflow.com/questions/51834482/angular-scss-global-variable-import

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!