返回
Vue-Class组件迁移到Vite的踩坑记录
前端
2023-11-05 21:46:39
Vite迁移中关于Vue-Class组件的踩坑记录与解决方案
迁移项目时,将Vue 2项目从Vue-CLI迁移到Vite时,由于项目使用了vue-class-component类组件进行TS支持,因此迁移过程并非一帆风顺。本文将分享遇到的踩坑以及解决方案,供其他开发者参考。
踩坑1:找不到vue-class-component
在迁移后,尝试运行项目时遇到了以下错误:
Could not find 'vue-class-component' in './node_modules'
这是因为Vue-CLI默认安装了vue-class-component,而Vite则没有。
解决方案:安装vue-class-component
可以通过以下命令安装vue-class-component:
npm install --save-dev vue-class-component
踩坑2:tsc编译错误
安装vue-class-component后,在运行tsc时遇到了以下错误:
error TS2304: Cannot find name 'ComponentOptions'.
这是因为vue-class-component需要使用特定的TypeScript装饰器来定义组件选项。
解决方案:安装@vue/component-compiler
要解决此错误,需要安装@vue/component-compiler
:
npm install --save-dev @vue/component-compiler
踩坑3:运行时错误
安装了@vue/component-compiler
后,在运行项目时遇到了以下错误:
Uncaught TypeError: Cannot read properties of undefined (reading 'componentFactory')
这是因为Vite默认使用Esm格式,而vue-class-component使用的是CommonJS格式。
解决方案:在Vite中使用CommonJS
要解决此错误,可以在Vite配置中启用CommonJS支持:
// vite.config.js
export default {
build: {
commonjsOptions: {
include: /node_modules/,
},
},
};
结论
通过上述解决方案,成功解决了项目迁移中遇到的关于Vue-Class组件的踩坑问题。需要注意的是,由于不同的项目配置和依赖项可能有所不同,因此在迁移过程中可能会遇到其他问题。建议仔细检查错误信息并搜索相关解决方案。希望本文对其他遇到类似问题的开发者有所帮助。