Angular组件的全局scss变量,而无需每次都导入 [英] Global scss variables for Angular components without importing them everytime

查看:207
本文介绍了Angular组件的全局scss变量,而无需每次都导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实已经在src/styles/settings/_variables.scss中定义了SCSS变量,并且将它们导入到src/styles.scss中,但是仍然不是每个组件都可以使用这些变量.

I do already have SCSS variables defined in src/styles/settings/_variables.scss and I am importing them into src/styles.scss, but still these variables aren't available for every single component.

是否有什么办法可以创建一个包含其他组件所有SCSS变量的全局文件?因为在每个单独的组件.scss文件中写入@import,这非常令人沮丧,尤其是在我有很多嵌套组件的情况下.

Is there any way to make a global file which holds all SCSS variables for the rest of my components? Because writing @import in every single component .scss file it is very frustrating, especially if I have many nested components.

我知道,有很多类似的问题,但似乎它们都已过时,并且与Angular的最新版本无关.

I know, there is a lot of similar questions, but it seems like they're all outdated and do not relate to the recent versions of Angular.

我将Angular 7.3与CLI一起使用.

I use Angular 7.3 with CLI.

推荐答案

您只需要添加一些配置,因此在声明全局变量的地方,需要将其包装在:root{}中.所以在src/styles/settings/_variables.scss.

You just need to add a little more config, so where you are declaring your global variables, you need to wrap it up in :root{}. So in src/styles/settings/_variables.scss.

:root 
{
--blue: #00b; // or any global you wish to share with components 
}

然后,当您在SCSS中使用它们时,您将需要像这样访问它们.

Then when you use them in the SCSS you will need to access them like so.

.example-class {
  background-color: var(--blue)
}

要添加有关注释的信息,此方法可以使用mixins@mediakeyframes,并且不仅限于颜色/字体.那是一个例子.

To add to this regarding comments, this method can use mixins, @media and keyframes and is not limited to just colours / font. That was an example.

据我所知,您需要一个全局文件src/assets/style/global,然后将每个scss文件导入到您在其中定义它们的位置.

From my understanding you need a global file src/assets/style/global and then to import each scss file into there where you are defining them like so.

@import 'filename';

如果您不希望在组件内使用全局变量,请在工作全局变量时查看.查看 ViewEncapsulation ,因为它可以用来忽略它们.

If you dont want global variables to be used in within a component look when you have the globals working. Look into ViewEncapsulation, as this can be used to ignore them.

这篇关于Angular组件的全局scss变量,而无需每次都导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆