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

如何在app.scss中正确调用_colors.scss内的SCSS map?

SCSS Map跨文件调用失败的解决方法

问题说明

我在_colors.scss文件中定义了SCSS Map,希望在app.scss文件中调用它,但尝试后无法成功使用,比如没法给.box类设置对应背景色,请问遗漏了什么?

原文件代码

_colors.scss

/*    Functions    */

@function color($elem, $variant) {
  @return map-get(map-get($color, $elem), $variant);
}

/*    Variables   */

$colors: (
  text: (
    1: #162c5b,
    2: #565678,
    3: #ababc9,
    soft: #718097,
    footer: #ff2a91,
    1i: #fff,
  ),
  bg: (
    hero: #038aff,
    awards: purple,
    features: #5ccaa7,
    tools: #febd3d,
    3: #d2daf0,
    infinite: #161348,
    footer: #161348,
    line-footer: #2f2c5b,
    pink: #f1ecfd,
    white: #fff,
  ),
);

app.scss

@use 'colors' as cl;


* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: "Inter", sans-serif;
}

.hero {
  width: 100%;
  .container {
    margin: 0 auto;
    padding: 90px 0;
    width: min(1200px, 100%);
    .box {
      width: 300px;
      height: 300px;
      padding: 28px;
      background-color: color(bg, hero);
      h2 {
        font-size: 2rem;
        padding-bottom: 20px;
        font-weight: 800;
      }
      p {
        font-size: 0.9rem;
        font-weight: 400;
        color: color(text, 1);
      }
    }
  }
}

错误原因及修正方案

1. 函数内变量名错误

_colors.scss中的color函数里,调用的是$color,但实际定义的Map变量是$colors(多了一个s),导致无法正确获取Map值。

修正后的_colors.scss函数部分:

@function color($elem, $variant) {
  @return map-get(map-get($colors, $elem), $variant);
}

2. 未使用导入的命名空间

使用@use 'colors' as cl;导入后,文件内的函数和变量都属于cl命名空间,直接调用color()会找不到该函数,必须加上命名空间前缀。

修正后的app.scss调用部分:

.box {
  width: 300px;
  height: 300px;
  padding: 28px;
  background-color: cl.color(bg, hero); // 加上cl.前缀
  h2 {
    font-size: 2rem;
    padding-bottom: 20px;
    font-weight: 800;
  }
  p {
    font-size: 0.9rem;
    font-weight: 400;
    color: cl.color(text, 1); // 加上cl.前缀
  }
}

可选:取消命名空间

如果不想使用命名空间,可以将导入语句改为@use 'colors' as *;,这样就可以直接调用color()而无需前缀,但推荐保留命名空间避免全局冲突。


内容的提问来源于stack exchange,提问作者Luis Alejandro Lopez de Anda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:34:51