You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从SASS局部文件重导出@use ... with定义的自定义变量?

解决Sass中@use自定义变量无法跨文件访问的问题

问题出在Sass的模块作用域规则上:用@use导入的模块,其内部变量默认是私有的,不会自动暴露给外部文件。你在theme.scss里只是通过@use '@material/theme' with (...)配置了Material主题,但并没有把自定义后的$surface等变量导出,所以其他文件@use 'theme.scss'后自然拿不到这些变量。

给你两种可行的解决方法:

方法一:手动导出需要的变量

在theme.scss中,先配置Material主题,再将需要外部使用的变量重新定义并导出:

// theme.scss
// 给Material主题模块起个命名空间(比如mdc-theme),方便引用内部变量
@use '@material/theme' as mdc-theme with (
  $background: #fff,
  $surface: #f0f6ff,
  $on-primary: #fff,
  $on-secondary: #fff,
);

// 导出自定义后的变量,供外部文件使用
$surface: mdc-theme.$surface;
$background: mdc-theme.$background;
// 按需添加其他需要导出的变量

然后在其他文件中:

// 导入theme模块并将变量全部引入当前作用域
@use 'theme.scss' as *;

.some-component {
  background-color: $surface; // 现在可以正常使用
}

方法二:用@forward转发配置后的主题变量

@forward可以将模块的变量、混合宏等转发出去,相当于把配置后的Material主题模块重新导出给外部使用:

// theme.scss
// 转发Material主题模块,同时配置自定义值
@forward '@material/theme' with (
  $background: #fff,
  $surface: #f0f6ff,
  $on-primary: #fff,
  $on-secondary: #fff,
);

如果只想转发特定变量,可以加上show关键字限制:

// theme.scss
@forward '@material/theme' with (
  $background: #fff,
  $surface: #f0f6ff,
  $on-primary: #fff,
  $on-secondary: #fff,
) show $surface, $background; // 只导出指定变量

然后在其他文件中:

// 方法2.1:通过命名空间访问变量
@use 'theme.scss' as theme;

.some-component {
  background-color: theme.$surface;
}

// 方法2.2:如果用了show指定变量,也可以用as *导入全部
@use 'theme.scss' as *;

.some-component {
  background-color: $surface;
}

内容的提问来源于stack exchange,提问作者Anentropic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:12:39