uni-app cli方式构建在main.js引入vant,运行npm run dev:app-plus报错 Cannot read property 'userAgent' of undefined

uni-app cli方式构建在main.js引入vant,运行npm run dev:app-plus报错 Cannot read property ‘userAgent’ of undefined

开发环境 版本号 项目创建方式
Windows win10 CLI

示例代码:

//导入vant
import Vant from "vant";  

//使用vant
Vue.use(Vant);
报错如下:  
Uncaught TypeError: Cannot read property 'userAgent' of undefined
at isIOS ()
at Module.<anonymous> ()
at webpack_require ()
at Module.<anonymous> ()
at webpack_require ()
at Module.<anonymous> ()
at webpack_require ()
at Module.<anonymous> ()
at webpack_require ()
at eval (main.js:4)

操作步骤:

  1. npm i vant -S
  2. main.js :
    //导入vant
    import Vant from "vant";  
    
    //使用vant
    Vue.use(Vant);
    
  3. npm run dev:app-plus
  4. 把dist/app-plus导入hbuilder
  5. 使用模拟器运行项目开启debugger调试报错

预期结果:

想要结果是想要在页面中可以正常使用:

<van-button type="primary">主要按钮</van-button>
<van-button type="info">信息按钮</van-button>
<van-button type="default">默认按钮</van-button>
<van-button type="warning">警告按钮</van-button>
<van-button type="danger">危险按钮</van-button>

实际结果:

实际报错: Uncaught TypeError: Cannot read property ‘userAgent’ of undefined at isIOS () at Module.<anonymous> () at webpack_require () at Module.<anonymous> () at webpack_require () at Module.<anonymous> () at webpack_require () at Module.<anonymous> () at webpack_require () at eval (main.js:4)

bug描述:

cli方式构建uniapp项目,默认模板,在main.js引入vant失败。打开app端运行报错,h5端运行没有问题:
Uncaught TypeError: Cannot read property ‘userAgent’ of undefined at isIOS () at Module.<anonymous> () at webpack_require () at Module.<anonymous> () at webpack_require () at Module.<anonymous> () at webpack_require () at Module.<anonymous> () at webpack_require () at eval (main.js:4)


更多关于uni-app cli方式构建在main.js引入vant,运行npm run dev:app-plus报错 Cannot read property 'userAgent' of undefined的实战教程也可以访问 https://www.itying.com/category-93-b0.html

9 回复

有人遇到过吗?

更多关于uni-app cli方式构建在main.js引入vant,运行npm run dev:app-plus报错 Cannot read property 'userAgent' of undefined的实战教程也可以访问 https://www.itying.com/category-93-b0.html


有人吗

楼主解决了么 我也遇到这个问题了

解决了吗

怎么样,解决了吗什么问题

我也是这个问题

楼主解决了没

兼容性的问题,app不兼容vant 你可以安装vant weapp 但是他又不支持h5

这个错误是因为 Vant 组件库在 App 端运行时尝试访问 navigator.userAgent 属性,但在 uni-app 的 App 环境中 navigator 对象可能未定义或与浏览器环境不同。

解决方案是使用条件编译按平台引入 Vant:

// main.js
// #ifdef H5
import Vant from 'vant';
import 'vant/lib/index.css';
Vue.use(Vant);
// #endif

对于 App 端,建议使用 uni-app 官方推荐的 UI 组件库,如 uni-ui 或 uView UI,这些组件库专门为 uni-app 多端兼容设计。

如果确实需要在 App 端使用 Vant,可以考虑以下替代方案:

  1. 使用 uni-app 的条件编译为不同平台提供不同的 UI 实现
  2. 使用 uni-ui 的按钮组件替代 Vant 按钮:
<uni-buttons>
  <button type="primary">主要按钮</button>
  <button type="default">默认按钮</button>
</uni-buttons>
回到顶部