【问题标题】:SASS/SCSS: @use variables defined to global namespace throwing "Undefined Variable" errorSASS/SCSS:@use 定义到全局命名空间的变量抛出“未定义变量”错误
【发布时间】:2021-02-21 20:07:01
【问题描述】:

我正在使用以下三个文件将 SCSS 文件编译为 CSS:

bootstrap/_variables.scss:

$font-color-root: #ff6d00;
$font-color-dark: #000;

主题/_theme.scss:

:root {
    --font-color: #{$font-color-root};
}
 
/* dark theme variables */
[data-theme=\'dark\'] { 
    --font-color: #{$font-colour-dark};
}

style.scss:

//import variables
@use 'bootstrap/variables' as *;

//import CSS files
@use 'themes/theme'; 

这一直抛出这个错误,很明显变量在theme.scss文件中是不可见的,如何让它们可见?

我认为全局命名空间可以解决这个问题。

Error: Undefined variable.
  ╷
2 │     --font-color: #{$font-color-root};
`

【问题讨论】:

  • 不要将 css 变量与 sass 变量结合起来。只需使用 sass 变量。另外css变量调用外的#也不需要,也会抛出错误。
  • @NathanielFlick 除非我弄错了,CSS 和 SASS 变量执行不同的功能。 CSS 变量对于浅色/深色主题是必需的。我看不到如何将它们彼此分开会导致功能性的浅色/深色主题 CSS 文件。至于 #{$var} 变量,该文档解释说这是 CSS 主题变量所必需的:sass-lang.com/documentation/breaking-changes/css-vars
  • 你在使用 dart-sass 吗?
  • @Arkellys 是的,没错
  • @NathanielFlick 我已经发布了使用如图所示格式的变量的解决方案,并且按照文档中的说明是正确的。

标签: sass


【解决方案1】:

我已经确定了解决方案:

引导程序/主文件:

$theme: "default";

//Import CSS file, pass the set $theme using `with ()`
@use 'themes/base_theme' with ($theme: $theme);

_base_theme.scss:

//theme will default to the value set here unless overwritten in the calling file using the `with` language construct
$theme: "default" !default;    

//gets vars with theme specified
@use '../bootstrap/variables' as vars with ($theme: $theme);

:root {
    --font-color: #{$font-color-root};
}

/* dark theme variables */
[data-theme=\'dark\'] { 
    --font-color: #{$font-colour-dark};
}

_variables.scss:

//Set Initial SCSS Variables
$theme: "default" !default;


$font-color-root: #000;
$font-color-dark: #fff;

//if theme is set to "not_default", change values
@if $theme == "not_default" {
    $font-color-root: #fff;
    $font-color-dark: #000;
}

总结:默认文件调用主题文件,在主题文件中,使用@use语言结构导入所需的变量。 @use 可以与with () 结合使用以覆盖默认变量设置(在这种情况下$theme 可以被覆盖)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 2019-05-08
    • 2022-06-14
    相关资源
    最近更新 更多