# HBuilderX小程序编译错误解决方案 ## 错误信息 ``` [vite]: Rollup failed to resolve import "@dcloudio/uni-ui/lib/uni-button/uni-button.vue" from "components/MsgTips/MsgTips.vue". [@vue/compiler-sfc] `defineExpose` is a compiler macro and no longer needs to be imported. [@vue/compiler-sfc] `defineProps` is a compiler macro and no longer needs to be imported. [@vue/compiler-sfc] `defineEmits` is a compiler macro and no longer needs to be imported. ``` ## 问题分析 ### 问题1:uni-button 组件未安装 **原因:** - `uni-button` 不是 uni-app 的内置组件 - 项目中使用了 `` 但没有安装 `@dcloudio/uni-ui` 完整包 - 只安装了部分组件(uni-popup、uni-icons等) **解决方案:** 使用原生 ` ``` **优点:** - ✅ 无需安装依赖 - ✅ 完全自定义样式 - ✅ 支持所有平台 - ✅ 性能更好 **缺点:** - ⚠️ 需要手动重置样式 - ⚠️ 需要自己实现 loading、disabled 等状态 ### uni-button ```vue 点击我 ``` **优点:** - ✅ 内置多种样式 - ✅ 自带 loading、disabled 状态 - ✅ 统一的UI风格 **缺点:** - ❌ 需要安装 uni-ui - ❌ 增加包体积 - ❌ 自定义样式受限 ## 📝 button 样式重置模板 推荐在全局样式中添加 button 重置: ```css /* App.vue 或 common.css */ /* 重置 button 默认样式 */ button { padding: 0; margin: 0; border: none; background: none; font-size: inherit; font-family: inherit; color: inherit; line-height: inherit; text-align: inherit; cursor: pointer; box-sizing: border-box; } /* 移除微信小程序 button 的默认边框 */ button::after { border: none; } /* 移除 button 按下时的背景色 */ button:active { background-color: inherit; } /* 通用按钮样式 */ .btn { display: inline-block; padding: 20rpx 40rpx; border-radius: 12rpx; text-align: center; transition: all 0.3s; } .btn-primary { background: linear-gradient(135deg, #13C57C 0%, #0FA368 100%); color: #FFFFFF; box-shadow: 0 8rpx 20rpx rgba(19, 197, 124, 0.3); } .btn-secondary { background: #F7F8FA; color: #666666; } ``` ## ⚠️ 注意事项 ### 1. 编译器宏的特殊性 ```javascript // ❌ 错误:不能解构或重命名 import { defineProps as props } from 'vue' // ❌ 错误:不能在条件语句中使用 if (someCondition) { defineProps({...}) } // ✅ 正确:直接在顶层使用 const props = defineProps({...}) ``` ### 2. TypeScript 支持 如果使用 TypeScript,编译器宏会自动获得类型支持: ```typescript ``` ### 3. 在非 setup 语法中 如果不使用 ` ``` ## ✅ 验证修复 修复后,重新编译项目应该看到: 1. ✅ 没有 "Rollup failed to resolve import" 错误 2. ✅ 没有 "defineXxx is a compiler macro" 警告 3. ✅ 小程序正常编译和运行 4. ✅ 按钮样式显示正常 ## 🔍 排查步骤 如果修复后仍然有问题: ### 1. 清除缓存 ``` HBuilderX: 运行 → 停止运行 工具 → 清除缓存 重新运行 ``` ### 2. 检查所有文件 使用全局搜索检查是否还有遗漏: ``` Ctrl + Shift + F 搜索: import.*defineProps 搜索: import.*defineEmits 搜索: import.*defineExpose ``` ### 3. 检查 pages.json 确保 easycom 配置正确: ```json { "easycom": { "autoscan": true, "custom": { "^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue" } } } ``` ### 4. 重新安装依赖 ```bash # 删除 node_modules 和 lock 文件 rm -rf node_modules rm package-lock.json # 重新安装 npm install ``` ## 📚 相关文档 - [Vue 3 script setup 文档](https://cn.vuejs.org/api/sfc-script-setup.html) - [uni-app button 组件](https://uniapp.dcloud.net.cn/component/button.html) - [uni-ui 文档](https://uniapp.dcloud.net.cn/component/uniui/uni-ui.html) - [Vite 构建优化](https://cn.vitejs.dev/guide/dep-pre-bundling.html) ## 🎉 总结 ### 问题 1. 使用了未安装的 `uni-button` 组件 2. 错误地从 vue 导入了编译器宏 ### 解决 1. ✅ 将 `` 替换为 `