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

使用Carbon框架编写SCSS时出现Undefined variable错误求助

解决SCSS编译错误:Undefined variable $carbon--theme--g100

错误原因

你的SCSS代码中引用的$carbon--theme--g100变量未被正确加载,问题出在Carbon主题的导入路径或版本不匹配上。

解决方案

1. 确认并安装依赖

先确保已安装@carbon/themes和carbon-components包:

npm install @carbon/themes carbon-components --save-dev

2. 根据Carbon版本修正代码

情况A:使用Carbon v10及以下(适配你的原始代码写法)

修正主题导入路径,将原导入语句替换为以下任一写法:

// 写法1:导入主题包入口文件
@import '@carbon/themes';

// 写法2:导入完整索引文件路径
@import '@carbon/themes/scss/index';

修正后的完整代码示例:

@import '@carbon/themes';

$carbon--theme: $carbon--theme--g100;
@include carbon--theme();

@import 'carbon-components/scss/globals/scss/styles.scss';

a {
  color: $text-04;
}

.bx--side-nav__navigation {
  background-color: $ui-background;
}

a.bx--side-nav__link--current,
a.bx--side-nav__link--current>span.bx--side-nav__link-text {
  background-color: $ui-01;
  color: $text-04;
}

.bx--side-nav__item:not(.bx--side-nav__item--active)>.bx--side-nav__link:hover {
  background-color: $ui-01;
  color: $text-04;
}

a.bx--side-nav__link>.bx--side-nav__link-text,
.bx--side-nav__item:not(.bx--side-nav__item--active)>.bx--side-nav__link:hover>span {
  color: $text-04;
}

情况B:使用Carbon v11+(最新版本)

v11采用@use替代@import,变量命名也做了简化,需同步调整代码:

@use '@carbon/themes' as themes;

$carbon--theme: themes.$g100;
@include themes.theme($carbon--theme);

@use 'carbon-components/scss/globals/styles';

a {
  color: themes.$text-04;
}

.bx--side-nav__navigation {
  background-color: themes.$ui-background;
}

a.bx--side-nav__link--current,
a.bx--side-nav__link--current>span.bx--side-nav__link-text {
  background-color: themes.$ui-01;
  color: themes.$text-04;
}

.bx--side-nav__item:not(.bx--side-nav__item--active)>.bx--side-nav__link:hover {
  background-color: themes.$ui-01;
  color: themes.$text-04;
}

a.bx--side-nav__link>.bx--side-nav__link-text,
.bx--side-nav__item:not(.bx--side-nav__item--active)>.bx--side-nav__link:hover>span {
  color: themes.$text-04;
}

3. 验证变量加载(可选)

若问题仍存在,可在导入主题后添加调试语句,确认变量是否成功加载:

@import '@carbon/themes';
@debug $carbon--theme--g100; // 编译时控制台会输出变量值,验证是否加载成功

4. 检查webpack配置(若使用webpack)

确保webpack的resolve配置能正确识别node_modules中的包:

module.exports = {
  resolve: {
    modules: ['node_modules'],
  },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:09:20