从 TypeScript 访问 SCSS 变量

Access SCSS variable from TypeScript

我正在 Angular 中创建自定义指令。我有一个带有变量的 SCSS 文件,如下图所示,我想将其导入我的指令 (.directive.ts)。我该怎么做?

谢谢

  1. 将它们写入列表的 custom CSS variables (you can use @each 规则):
:root {
  --bs-light: #f1f2f3;
  --bs-dark: #3e3e3c;
}
  1. 使用此代码从文档中读取变量:
export enum ScssVariables {
    Light = "light",
    Dark = "dark",
}

@Directive({
    selector: "[test-attr]",
})
export class TestDirective {
    public styles: { [key in ScssVariables]: string | null } = {
        light: null,
        dark: null,
    };

    constructor() {
        const styles = window.getComputedStyle(document.body);
        Object.keys(this.styles).forEach((key: ScssVariables) => {
            this.styles[key] = styles.getPropertyValue("--bs-" + key);
        })
        console.log(this.styles);
    }
}