uni-app vue3+vite微信小程序混合打包无法运行报 '$createComponent' of undefined
uni-app vue3+vite微信小程序混合打包无法运行报 ‘$createComponent’ of undefined
项目名称 | 产品分类 | 创建方式 | CLI版本号 |
---|---|---|---|
无 | uniapp/小程序/微信 | CLI | 3.0.0-alpha-3031320220314002 |
操作步骤:
- npx degit dcloudio/uni-preset-vue#vite my-vue3-project
- yarn yarn build:mp-weixin --subpackage=test
- 集成到原生微信小程序,运行
预期结果:
正确打开uniapp的页面
实际结果:
报如下错误
VM760 WAService.js:2 TypeError: Cannot read property '$createComponent' of undefined
at $vm.type (vendor.js? [sm]:1)
at se.attached (vendor.js? [sm]:1)
at n.safeCallback (VM760 WAService.js:2)
at n.call (VM760 WAService.js:2)
at n (VM760 WAService.js:2)
at E (VM760 WAService.js:2)
at Function.Q.pretendAttached (VM760 WAService.js:2)
at Module.We (VM760 WAService.js:2)
at Le (VM760 WAService.js:2)
at VM760 WAService.js:2
bug描述:
使用最新的cli版本进行微信小程序的混合打包运行,运行时报下面的错误,无法正常运行
TypeError: Cannot read property '$createComponent' of undefined
at $vm.type (vendor.js? [sm]:1)
at se.attached (vendor.js? [sm]:1)
at n.safeCallback (VM760 WAService.js:2)
at n.call (VM760 WAService.js:2)
at n (VM760 WAService.js:2)
at E (VM760 WAService.js:2)
at Function.Q.pretendAttached (VM760 WAService.js:2)
at Module.We (VM760 WAService.js:2)
at Le (VM760 WAService.js:2)
at VM760 WAService.js:2
其他形式的打包运行没有问题
在使用 uni-app 结合 Vue 3 和 Vite 开发微信小程序时,遇到 '$createComponent' of undefined
的错误,通常是因为 Vue 3 的某些特性在小程序环境中不完全兼容,或者构建配置中存在问题。以下是一些可能的解决方案和排查步骤:
1. 确保依赖版本兼容
确保你使用的 uni-app
、vue
、vite
以及相关插件的版本是兼容的。特别是 @dcloudio/uni-app
和 vite-plugin-uni
的版本需要支持 Vue 3。
推荐使用以下版本:
"dependencies": {
"vue": "^3.2.0",
"@dcloudio/uni-app": "^3.0.0-alpha-3070720220509001",
"vite": "^2.6.0"
},
"devDependencies": {
"vite-plugin-uni": "^2.0.0"
}
2. 检查构建配置
确保 vite.config.js
中正确配置了 vite-plugin-uni
,并且针对微信小程序的配置没有问题。
示例配置:
import { defineConfig } from 'vite';
import uni from 'vite-plugin-uni';
export default defineConfig({
plugins: [uni()],
});
3. 检查 Vue 3 的全局 API 使用
Vue 3 的全局 API 与 Vue 2 不同,尤其是 createApp
和 createComponent
。确保在代码中正确使用了 Vue 3 的 API。
例如:
import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app');
4. 排查小程序环境兼容性
微信小程序的环境与浏览器环境有所不同,某些 Vue 3 的特性可能在小程序中无法正常工作。可以尝试以下方法:
- 避免使用 Vue 3 的 Composition API 中的
ref
、reactive
等特性,改用 Options API。 - 检查是否使用了小程序不支持的 API 或语法。
5. 清理缓存并重新构建
有时候构建缓存会导致问题,可以尝试清理缓存并重新构建:
rm -rf node_modules/.vite
rm -rf dist
npm install
npm run build
6. 检查 uni-app 的运行时
确保 uni-app 的运行时正确加载。可以在 main.js
或 main.ts
中检查是否导入了 @dcloudio/uni-app
的运行时。
例如:
import { createSSRApp } from 'vue';
import App from './App.vue';
export function createApp() {
const app = createSSRApp(App);
return { app };
}