DEBUG.WIKI
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →

解决 Vite 报错 Failed to resolve import 路径别名修复

排查 Vite 开发服务器启动或热更新提示 [vite] Internal server error: Failed to resolve import '@/utils/api',配置 resolve.alias 与 tsconfig 映射。

问题现象

在启动 Vite 开发服务器或保存文件触发 HMR 时,浏览器弹窗或终端打印错误:

[vite] Internal server error: Failed to resolve import "@/components/Button" 
from "src/App.vue". Does the file exist?
  Plugin: vite:import-analysis
  File: /Users/dev/my-project/src/App.vue:2:24

触发根因

  1. Vite 配置文件中缺少路径别名(Alias)映射:开发者习惯在代码中使用 @ 代表 src 目录,但 Vite 默认并不自带该别名解析逻辑;
  2. 文件扩展名省略(Extensions):代码中书写了 import './style' 但未标明 .css 后缀,而 Vite 默认不对非 JS/TS 文件执行后缀自动盲猜补全;
  3. 操作系统大小写敏感差异(例如代码中写 button 而实际磁盘文件为 Button.vue)。

解决步骤

1. 在 vite.config.ts 中配置 resolve.alias

使用 Node.js 的 path 模块绑定 @ 指向物理绝对路径:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
});

2. 同步在 tsconfig.json 中配置 paths

保证 TypeScript 编译器与 IDE 编辑器也能精准索引符号:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

验证确认

在终端启动 Vite 开发服务器:

npx vite --port 3000

控制台成功打印 ready in 210 ms,浏览器打开页面所有使用 @/ 别名的组件顺利加载。