从零搭建Vue3项目遇到的5个典型报错及解决(附解决方案)

1,057 阅读2分钟

image.png

前言

本文将分享5个最常见的报错及其解决方案

报错一:Cannot find module 'vue' 依赖安装失败

🚨 报错场景

npm install vue
# 安装后运行项目仍提示模块缺失

🔍 原因分析

Vue3项目需要配合新版脚手架:

  • 使用Vite而非vue-cli
  • 依赖包命名规则变化

✅ 正确操作

# 使用官方推荐命令创建项目
npm create vite@latest my-vue-app -- --template vue-ts

# 安装核心依赖(注意包名差异)
npm install vue@next @vue/compat @vue/compiler-sfc

关键差异说明:

vue2vue3
vue-template-compiler@vue/compiler-sfc
vuexpinia

报错二:TS类型错误 Property 'xxx' does not exist on type...

🚨 典型报错

// 组件实例类型缺失
const instance = getCurrentInstance()
console.log(instance.proxy.$router) // TS报错

🔍 解决方案

方法1:类型断言

import { ComponentInternalInstance } from 'vue'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
console.log(proxy?.$router)

方法2:自定义类型声明(推荐)

// src/types/vue.d.ts
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $router: Router
    $api: AxiosInstance
  }
}

报错三:Uncaught ReferenceError: require is undefined

🚨 错误场景

在Vite项目中使用CommonJS模块:

const module = require('./module') // 引发报错

🔍 根本原因

Vite默认使用ES Module规范,不支持require

✅ 现代化改造方案

步骤1:修改引入方式

import module from './module.ts'

步骤2:改造package.json

{
  "type": "module" // 声明ESM规范
}

步骤3:动态导入(按需使用)

const module = await import('./module.ts')

报错四:Failed to resolve component: xxx 组件注册失败

🚨 典型症状

<template>
  <MyComponent /> <!-- 控制台警告 -->
</template>

🔍 原因排查

  1. 组件未注册
  2. <script setup>语法糖的特殊性

✅ 最佳实践

全局注册(适用于高频组件)

// main.ts
import MyComponent from '@/components/MyComponent.vue'

const app = createApp(App)
app.component('MyComponent', MyComponent)

局部注册(推荐方式)

<script setup>
// 自动注册组件(需遵循命名规范)
import MyComponent from '@/components/MyComponent.vue'
</script>

文件名规范建议:

components/
├─ base/
│  └─ BaseButton.vue  // 基础组件
├─ business/
│  └─ ProductCard.vue // 业务组件

报错五:Uncaught SyntaxError: Unexpected token '??=' 构建错误

🚨 构建时报错

npm run build
# 出现ES2021语法兼容问题

🔍 兼容性方案

方案1:修改构建目标

// vite.config.js
export default defineConfig({
  build: {
    target: 'es2020' // 降低ES版本
  }
})

方案2:添加polyfill

npm install core-js
// main.ts
import 'core-js/stable'

项目优化彩蛋 🎁

推荐VSCode插件

  1. Volar - Vue3官方语言支持
  2. ESLint - 代码规范检查
  3. Error Lens - 实时错误提示

项目结构

src/
├─ assets/       # 静态资源
├─ components/   # 公共组件
├─ composables/  # 组合式API
├─ router/       # 路由配置
├─ store/        # 状态管理
├─ types/        # TS类型声明
└─ views/        # 页面组件