如何解决Vite+TypeScript项目的‘Cannot find module’与‘noEmit’问题
解决路径别名@/*无法解析的问题
问题描述
已在tsconfig.json和vite.config.ts中配置@/*指向./src/*的路径别名,但仍报错:Cannot find module '@/lib/utils',TypeScript与Vite均未正确解析该别名。
配置文件与报错截图
根目录tsconfig.json
{ "files": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" } ], "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["./src/*"] } } }
vite.config.ts
import react from "@vitejs/plugin-react"; import path from "path"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [react()], resolve: { alias: { "@": path.resolve(__dirname, "./src"), }, }, });
解决步骤
同步子TS配置文件:因为根
tsconfig.json使用了references,实际生效的是tsconfig.app.json这类子配置文件。需在子配置中添加相同的baseUrl和paths,或通过extends继承根配置:// tsconfig.app.json示例 { "extends": "./tsconfig.json", "compilerOptions": { // 保留原有配置 }, "include": ["src/**/*"] }若子配置已有
compilerOptions,需确保baseUrl和paths未被覆盖。重启TypeScript服务:在VSCode中按下
Ctrl+Shift+P(Mac为Cmd+Shift+P),输入TypeScript: Restart TS Server清除缓存。校验文件路径与大小写:确认
src/lib/utils.ts(或.tsx)文件存在,且代码中引用的路径大小写与实际文件一致(Linux/macOS环境区分大小写)。确认Vite路径有效性:检查
path.resolve(__dirname, "./src")是否指向正确的src目录,确保vite.config.ts与src文件夹在同一层级。
内容的提问来源于stack exchange,提问作者Muhammad Saim
相关产品推荐
相关产品推荐

