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

查看:57
本文介绍了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天全站免登陆