You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vite运行Vue3项目报Failed to resolve import导入错误如何解决

Vite 环境下路由懒加载组件导入解析失败修复

报错信息

基于Vue 3 + Vite + Tailwind CSS栈开发的项目启动时持续抛出构建错误:

[plugin:vite:import-analysis] Failed to resolve import "../../views/main/index" from "src/router/module/mobile-routes.js". Does the file exist?

关联代码

路由入口文件 src/router/index.js

import { createRouter, createWebHistory } from 'vue-router'
import { isMobileTerminal } from '../utils/flexible'
import mobileRoutes from './module/mobile-routes'
import pcRoutes from './module/pc-routes'

// 创建vueRouter实例
const router = createRouter({
  history: createWebHistory(),
  routes: isMobileTerminal.value ? mobileRoutes : pcRoutes
})

export default router

移动端路由配置 src/router/module/mobile-routes.js

export default [
  {
    path: '/', // 路由路径
    name: 'home', // 路由名称
    component: () => import('../../views/main/index') // 懒加载对应组件
  }
]

对应页面组件 src/views/main/index.vue

<template>
  <div>
    移动端首页
  </div>
</template>

<script setup>
export default {
  name: 'index'
}
</script>

<style lang="scss" scoped></style>

问题原因

Vite的静态导入解析规则和Webpack存在差异,默认不会自动补全.vue后缀的文件路径。当前导入路径写为../../views/main/index时,Vite只会查找无后缀的index文件,不会匹配同目录下的index.vue,因此触发解析失败报错。

修复方案

两种方案选择其一即可:

  • 直接修改导入路径,显式补全.vue后缀,改动量最小:
export default [
  {
    path: '/',
    name: 'home',
    component: () => import('../../views/main/index.vue')
  }
]
  • 在vite.config.js中配置后缀自动解析规则,适配原有省略后缀的写法:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    // 注意:配置该项会覆盖Vite默认后缀列表,需把默认支持的后缀一并写入
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
  }
})

内容的提问来源于stack exchange,提问作者Charlene

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 03:27:23