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

Vue 2项目中如何修改BalmUI的font-family及其他Sass变量

解决方案:Vue 2 + BalmUI 本地字体引入与Sass变量定制

1. 修正BalmUI引入方式,移除冲突CSS导入

打开main.js,删除import 'balm-ui-css';(直接导入预编译CSS会和自定义Sass样式冲突),修改后代码如下:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import BalmUI from 'balm-ui';
import BalmUIPlus from 'balm-ui-plus';

Vue.use(BalmUI);
Vue.use(BalmUIPlus);

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

2. 在Sass中正确引入本地字体并覆盖变量

编辑app/styles/global/_vendor.scss,先定义本地字体,再覆盖Material排版变量,最后引入BalmUI源码:

// 1. 定义本地字体(路径基于public目录,Vue CLI会自动识别静态资源根目录)
@font-face {
  font-family: 'CustomFont';
  src: url('/fonts/font-name.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

// 2. 覆盖Material typography变量,替换为自定义字体
@use '@material/typography/typography' with (
  $font-family: string.unquote('CustomFont, Roboto, sans-serif'),
);

// 3. 引入BalmUI的Sass源码(使用源码而非预编译文件,支持变量定制)
@use 'balm-ui/src/styles/balm-ui';

3. 导入自定义Sass到项目入口

在main.js末尾添加一行,让Webpack自动编译并注入自定义样式:

import './app/styles/global/_vendor.scss';

4. 移除错误的HTML样式引用

打开public/index.html,删除<link rel="stylesheet" href="%PUBLIC_URL%/styles/main.css" />——Vue CLI会自动处理Sass编译和样式打包,该手动引用的文件不会自动生成,会导致报错。

5. 优化vue.config.js配置(可选)

若遇到Sass模块导入路径问题,可添加Sass的includePaths确保依赖能被正确识别,同时删除无用的balm-ui-css别名:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  runtimeCompiler: true,
  configureWebpack: {
    resolve: {
      alias: {
        'balm-ui-plus': 'balm-ui/dist/balm-ui-plus.js'
      }
    }
  },
  css: {
    loaderOptions: {
      sass: {
        includePaths: [
          './node_modules/@material',
          './node_modules/balm-ui/src/styles'
        ]
      }
    }
  }
})

完成以上步骤后,重启Vue CLI服务(npm run serve),自定义字体即可正常加载,BalmUI组件会自动应用你设置的Sass变量,同时不会再出现文件不存在的报错。

内容的提问来源于stack exchange,提问作者hamid-davodi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 13:53:28