uniapp app平台 v3 模式暂不支持在 js 文件中引用"./theme-light.scss" 该怎么修改?

在uniapp的app平台使用v3模式开发时,遇到js文件中引用"./theme-light.scss"报错不支持的问题。请问该如何修改才能正确引用scss文件?目前需要获取scss中的变量值用于js逻辑处理,希望有经验的开发者能提供解决方案。

2 回复

在js文件中无法直接导入scss文件。建议将样式变量提取到单独的js文件中导出,然后在js和scss中分别引用这个js文件。


在 UniApp 的 V3 编译模式下,由于平台限制,直接在 .js 文件中引用 .scss 文件会报错。以下是解决方案:

1. 将样式文件改为全局引入

  • App.vue<style> 标签中引入 SCSS 文件:
<style lang="scss">
@import './theme-light.scss';
</style>

2. 通过 CSS 变量实现主题切换

  • theme-light.scss 中定义 CSS 变量:
:root {
  --primary-color: #007AFF;
  --bg-color: #FFFFFF;
}
  • 在页面样式中使用变量:
.page {
  background-color: var(--bg-color);
  color: var(--primary-color);
}

3. 使用 Vuex 管理主题状态

  • 在 Vuex 中存储主题配置:
// store/index.js
export default new Vuex.Store({
  state: {
    theme: 'light'
  },
  mutations: {
    setTheme(state, theme) {
      state.theme = theme
    }
  }
})

4. 动态切换类名

  • 在页面模板中动态绑定类名:
<template>
  <view :class="['page', theme]">
    <!-- 页面内容 -->
  </view>
</template>

<script>
import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState(['theme'])
  }
}
</script>

<style lang="scss">
.page.light {
  @import './theme-light.scss';
}
.page.dark {
  @import './theme-dark.scss';
}
</style>

注意事项:

  • 确保已安装 sasssass-loader 依赖
  • 检查 vue.config.js 中是否正确配置了 SCSS
  • 使用条件编译区分平台(如需要)

这样即可在 V3 模式下正常使用 SCSS 主题文件。

回到顶部