使用绝对路径导入JSON文件时出现Cannot find module错误
问题:使用绝对路径导入JSON文件时出现
Cannot find module ... or its corresponding type declarations错误 我在尝试导入JSON文件时遇到错误:Cannot find module ... or its corresponding type declarations。已经把所有JSON文件迁移到data文件夹,并且尝试在vite.config.ts和tsconfig.json中配置绝对路径。使用绝对路径时有自动补全功能,但仍然报错;改用相对路径(比如../../../assets/data/aboutData.json)代码就能正常运行。请问需要调整导入策略或配置文件的哪些内容才能解决这个问题?
相关代码片段
About.tsx(错误出现在第1行)
import aboutData from 'src/assets/data/aboutData.json'; import { Card } from './Card' export function About() { return ( <div> {aboutData.map((item, index) => { return ( <Card key={index} img={item.img} cardHeading={item.title} cardText={item.body} /> ); })} </div> ); }
aboutData.json
[ { "id": /* id */, "img": /* image path */, "title": /* title */, "body": /* text body */ }, // 剩余JSON内容 ]
vite.config.ts
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], resolve: { alias: { src: './src', }, }, });
tsconfig.json
{ "compilerOptions": { // 其他配置项 "baseUrl": ".", "paths": { "src/*": ["/src/*"] } }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] }
解决方案
修正
tsconfig.json路径配置
你的paths配置里的/src/*多了前置斜杠,导致路径解析错误,改成相对路径格式:{ "compilerOptions": { // 其他配置项 "baseUrl": ".", "paths": { "src/*": ["src/*"] } }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] }添加JSON模块类型声明
TypeScript无法自动识别JSON模块类型,在src目录下创建types/json.d.ts文件:declare module '*.json' { const value: any; export default value; }同时更新
tsconfig.json的include字段,确保类型文件被识别:"include": ["src", "src/types/**/*.d.ts"]优化Vite别名配置(可选)
使用path.resolve确保路径解析无歧义:import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import path from 'path'; export default defineConfig({ plugins: [react()], resolve: { alias: { src: path.resolve(__dirname, './src'), }, }, });重启服务与IDE
修改配置后必须重启Vite开发服务器和IDE,确保新配置生效。
内容的提问来源于stack exchange,提问作者JordanH
相关产品推荐
相关产品推荐

