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

ReactJS迁移Vite后如何实现省略index.js的无相对路径导入

解决Vite中无相对路径前缀导入src目录模块的问题

1. 配置jsconfig.json(JavaScript项目)

在项目根目录创建或修改jsconfig.json,让编辑器能识别src下的模块路径:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

如果是TypeScript项目,直接修改tsconfig.json的compilerOptions部分,同样设置baseUrl: "./src"即可。

2. 配置vite.config.js

修改vite.config.js,让Vite能正确解析src下的模块:

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

export default defineConfig({
  plugins: [react()],
  resolve: {
    // 让Vite解析模块时优先查找src目录
    modules: [path.resolve(__dirname, './src'), 'node_modules'],
    // 自动识别这些后缀的文件,无需手动指定index.js
    extensions: ['.js', '.jsx', '.json']
  }
});

3. 验证效果

配置完成后,就可以像react-scripts中那样直接导入:

import Routes from 'routes';
import Themes from 'themes';

Vite会自动匹配src/routes/index.js和src/themes/index.js文件。

常见排查点

  • 编辑器报错的话,重启编辑器让配置生效
  • 确认src下的目标子目录确实存在index.js文件
  • 检查vite.config.js中的路径是否正确,比如path.resolve(__dirname, './src')是否指向项目的src目录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 02:42:09