尽管其他样式有效,但无法在全局文件的 Angular 中使用 SASS 变量

Can't use SASS variables in Angular from global file, despite other styles working

当我在我的组件样式中应用以下 SASS 时,它按预期工作。

$test-color: pink;
div{ background-color: $test-color; }

但是,当我将定义移动到 styles.scss 时,它不会。我已经尝试添加(现在,apparently,已弃用)@import "../styles.scss"; 以及当前推荐的 @use "../styles.scss";。我什至尝试将颜色定义放入 colors.scss 并将该引用添加到 angular.json。在 styles.scss 中声明的 类 的样式有效(即使没有 importing/using,因为它是资产中的引用)。但是变量没有。

根据 this suggestion, it should work with @include. In this docs, it's shown how to assign the values. I found this linking to but I can't see how that differs from my case. I tried to understand this blog but couldn't see any relevant hints on what I'm doing wrong. I also tried adding the following (as shown here).

"stylePreprocessorOptions": { "includePaths": [ "src" ] }

不过,我仍然收到以下错误。

ERROR in ./src/app/.../some.component.scss
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Undefined variable.
14 │ background-color: $test-color;
___ │ _________________ ^^^^^^^^^^^^
src\app...\some.component.scss 14:23 root stylesheet

谷歌搜索实际错误给了我 saying that the variable isn't there. But as far I can tell, it is! A related, although a bit different, question was asked here 但没有相关答案。

我遗漏了什么,我该如何进一步调查?

错误是由于所指出的语法错误造成的。它需要参考颜色的来源。

background-color: colors.$test-color;

此外,导入是必需的,但需要通过引用模块而不是文件来完成。

@use "colors";

在完整的代码库中,应该将以下内容放入文件 src\colors.scss.

$test-color: pink;

那你就可以这样用了

@use "colors";
div{ background-color: colors.$test-color; }

在配置文件angular.json中,需要设置以下内容。

"styles": { ... },
"stylePreprocessorOptions": { "includePaths": [ "src" ] },
"scripts": { ... },

此外,应该注意以下划线前缀的文件会受到不同的处理,因此,_colors.scss 是首选。虽然将辅助文件直接放在 /src 中是有效的并且可以工作(就像 styles.scss 的情况一样,约定规定将它们放在 /src/assets/styles 中,如下所示更改预处理器的选项。

"stylePreprocessorOptions": { "includePaths": [ "src/asses/styles" ] }