uni-app中uni.scss条件编译不生效

uni-app中uni.scss条件编译不生效

开发环境 版本号 项目创建方式
Windows win10 HBuilderX
产品分类:uniapp/H5

浏览器平台:Chrome
浏览器版本:92.0.4515.131

示例代码:
/* #ifdef MP-ALIPAY */
[@import](/user/import) './common/nh.scss';
/* #endif */

/* 行为相关颜色 */
$uni-color-primary: #007aff;
$uni-color-success: #4cd964;
$uni-color-warning: #f0ad4e;
$uni-color-error: #dd524d;

操作步骤:

```scss
/* #ifdef MP-ALIPAY */
[@import](/user/import) './common/nh.scss';
/* #endif */

预期结果:

仅在支付宝引用该scss文件

实际结果:

所有平台都引用了

bug描述:

uni.scss里面不支持条件编译,在uni.scss里使用了条件编译,仅在支付宝小程序引入的scss文件,在h5端也引用了

更多关于uni-app中uni.scss条件编译不生效的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app中uni.scss条件编译不生效的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在 uni-app 中,uni.scss 文件本身不支持条件编译。这是因为 uni.scss 是一个全局的样式文件,在编译时会被所有平台处理,其中的条件编译指令不会被正确解析。

解决方案:

  1. 使用平台特定的样式文件:

    • 创建 uni.scss 文件,定义全局变量。
    • App.vue 或页面组件中,通过条件编译引入平台特定的样式文件。
    • 例如,在 App.vue<style> 标签中:
      /* #ifdef MP-ALIPAY */
      @import './common/nh.scss';
      /* #endif */
      
  2. 在页面或组件中条件编译:

    • 如果样式仅针对特定页面,可以在该页面的 <style> 标签中使用条件编译。
    • 例如:
      /* #ifdef MP-ALIPAY */
      .custom-style {
        color: red;
      }
      /* #endif */
      
  3. 使用动态类名或样式绑定:

    • 通过 JavaScript 判断平台,动态添加类名或样式。
    • 例如,在 Vue 模板中:
      <template>
        <view :class="{'alipay-style': isAlipay}">内容</view>
      </template>
      <script>
      export default {
        computed: {
          isAlipay() {
            return uni.getSystemInfoSync().platform === 'alipay';
          }
        }
      }
      </script>
      <style>
      .alipay-style {
        color: red;
      }
      </style>
回到顶部