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

禁用相对导入后出现TS2307找不到本地模块错误,如何解决?

非相对路径导入触发TS2307报错排查项
  • 首先确认构建工具同步配置了根目录解析规则
    TypeScript的baseUrl仅作用于类型检查阶段,实际构建的路径解析由你的打包工具负责,需要对应配置:
    • Webpack:在webpack.config.js的resolve.modules中新增src目录路径,示例:
      const path = require('path');
      module.exports = {
        resolve: {
          modules: [path.resolve(__dirname, 'src'), 'node_modules'],
          extensions: ['.ts', '.tsx', '.js', '.jsx']
        }
      }
      
    • Vite:在vite.config.ts中配置resolve.alias指向src目录,示例:
      import { defineConfig } from 'vite'
      import path from 'path'
      export default defineConfig({
        resolve: {
          alias: {
            '/': path.resolve(__dirname, 'src')
          }
        }
      })
      
    • 未eject的Create React App项目:需要通过craco、react-app-rewired等工具修改默认的webpack配置,新增src目录解析规则。
  • 补充tsconfig的paths配置
    在tsconfig.json的compilerOptions中新增如下配置,明确非相对路径的解析规则:
    "paths": {
      "*": ["*"]
    },
    "moduleSuffixes": [".ts", ".tsx", ".js", ".jsx"]
    
  • 检查导入路径和实际文件结构匹配度
    配置baseUrl: "src"后,非相对导入的路径需要完全匹配src下的目录结构,例如:
    • 若文件路径为src/card.tsx,import card from 'card'写法有效
    • 若文件路径为src/components/card.tsx,需要写为import card from 'components/card'
  • 检查IDE的TypeScript配置
    如果使用VS Code,可按以下步骤排查:
    1. 按下Ctrl+Shift+P(Mac为Command+Shift+P),选择「TypeScript: Select TypeScript Version」,切换为项目本地的工作区版本
    2. 选择「TypeScript: Restart TS Server」重启TypeScript服务,确保配置生效
  • 检查ESLint导入插件配置(若使用eslint-plugin-import)
    在.eslintrc的settings中新增如下配置,让ESLint识别src根目录解析规则:
    "settings": {
      "import/resolver": {
        "node": {
          "paths": ["src"],
          "extensions": [".ts", ".tsx", ".js", ".jsx"]
        }
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:06:05