0

我致力于选择使用 SASS 的多租户应用程序的样式。遵循最新版本指南,我开始使用@use和构建基本样式@forward。现在我想用客户的颜色和字体变量来主题化这个基础,以接收多个样式表,这些样式表可以提供给我们应用程序的不同实例。

如果我要使用 deprecated @import,我会这样:

styles/customerA/index.scss

@import "customerA-variables";
@import "../base/index";

但是有了新规则,我找不到一种简单的方法来简单地将主题特定变量提供给基本样式。我尝试使用with关键字,但事实证明我需要在模块中定义变量,而我宁愿将它们封装在另一个模块中并导入它。

styles/customerA/index.scss

@use "customerA-variables" as variables;
@use "../base/index" with (
  $bgColor: variables.$bgColor,
  $textColor: variables.$textColor
);

styles/base/_base-variables.scss

$bgColor: #eee !default;
$textColor: #333 !default;
styles/base/index.scss

/* HOW IT WORKS */
$bgColor: #eee !default;
$textColor: #333 !default;

/* HOW I WISH IT WORKED */
@use "./base-variables" as *;

/* LATER IN THE FILE */
body {
  background-color: $bgColor;
  color: $textColor;
}

@use "../variables" as *场景中我收到此错误:

Error: This variable was not declared with !default in the @used module.

我正在寻找一个可行的解决方案,最好不要在with括号内复制粘贴所有主题变量。

4

1 回答 1

2

首先是错误:

错误:此变量未在 @used 模块中使用 !default 声明。

当您尝试@use使用配置变量的模块/文件但配置变量未设置为!default模块/文件中的变量时,会出现该错误。因此,SASS 检查您是否传递了未提供给模块配置的配置。这对您来说是额外的安全保障。

我不太确定我是否正确理解了您的示例,但可能是这样:

// styles/customerA/index.scss

@use "customerA-variables" as variables;
@use "../base/index" with (
  $bgColor: variables.$bgColor,
  $textColor: variables.$textColor
);

--> SASS ERROR because $bgColor and/or $textColor
--> in @used module/file are not set as defaults, i.e.:
--> $bgColor: green;
--> must be: $bgColor: green !default;

因此,您可以检查模块是否所有变量都设置为默认值并且没有被非默认值覆盖。

**第二:用法@use

新规则@use确实令人困惑......在您的示例中导致代码加倍:一次是在您设置自定义变量时customerA-variables.scss,然后在您@use在模块/文件中重复该变量时styles/customerA/index.scss(请参阅您的第二个代码示例)。

避免重复代码的一个好方法是准备一个配置文件,其中包含单个客户的设置,而@use不是配置文件(不是直接想要的模块/文件)。

例子:


// ###
// ### module/file: ../base/index.scss

$bgColor: #eee !default;
$textColor: #333 !default;

body {
  background-color: $bgColor;
  color: $textColor;
}



// ### 
// ### customer configuration file: configModuleCustomerA.scss

@forward "../base/index" with (
  $bgColor: red,
  $textColor: blue
);



// ###
// ### use that configuration file 
// ### to your main file: styles/customerA/index.scss

@use "...path.../configModuleCustomerA" as *;

// Note:
// 1. that writes the configurated css
// 2. and it provides the variables for additional use to THIS file
// see going on this file below ...

.additionalElement {
   background: $bgColor;
   color: $textColor;
}
   
   
// ### 
// ### ---> that compiles to CSS:

body {
  background-color: red;
  color: blue;
} 

.additionalElement {
   background: red;
   color: blue;
}


注意:您应该知道一个额外的技巧/效果。

您只需要设置一次变量……就在您配置模块/文件的时候。当您在/模块配置文件中执行此操作时,您在那里设置的变量是您项目配置的一部分!

因此,如果您第二次/第三次/...时间(即在附加的部分文件中)需要模块的 SAME 变量,则@use该配置文件位于您需要它/它们的任何文件中。别担心:css 代码只编译一次到你的 CSS:第一次你@use的模块。

但请注意您的情况:

但是如果你想要@use一个具有不同配置的模块/文件,你必须将它编译成两个不同的 CSS 文件。一个具有两个或多个不同配置的模块加载到同一个 CSS 中会被 SASS 阻止。在这种情况下,您需要将 css 拆分为不同的客户 css 文件,这些文件都使用不同的模块配置文件。

于 2021-04-08T12:04:46.163 回答