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

Vite+TanStack Router开发SPA时package.json配置冲突问题求助

解决方案

核心是保留package.json中的"type": "module"(Vite官方推荐的ES模块模式),同时解决TypeScript的模块解析冲突问题,具体步骤如下:

  1. 调整TypeScript模块解析配置
    在tsconfig.json的compilerOptions中添加/修改以下规则:

    {
      "compilerOptions": {
        "moduleResolution": "bundler",
        "module": "ESNext",
        "target": "ESNext"
      },
      "include": [
        "src/**/*",
        "./routeTree.gen.ts"
      ]
    }
    
    • moduleResolution: "bundler"让TypeScript采用和Vite一致的模块解析逻辑,无需在导入时手动添加.js后缀。
    • include数组明确包含生成的路由文件,确保TypeScript能识别到它的类型声明。
  2. 确认TanStack Router插件的代码生成格式
    确保TanStackRouterVite插件生成TypeScript格式的路由文件,可在Vite配置中明确指定:

    // vite.config.ts
    TanStackRouterVite({
      routesDirectory: './src/routes', // 你的路由文件根目录
      generatedRouteTree: './routeTree.gen.ts', // 指定生成ts格式文件
    })
    

    插件会自动同步生成对应的类型声明文件,避免导入时的类型报错。

  3. 修复Vite配置文件的类型提示
    启用"type": "module"后,只要tsconfig.json的module和target配置为ESNext,Vite会自动以ES模块方式解析配置文件,defineConfig的类型提示就会恢复正常。如果仍有问题,可将vite.config.ts改名为vite.config.mts,明确标记为ES模块类型的TypeScript配置文件。

以上方案完全适配Vite和TanStack Router的最佳实践,可同时解决两个文件的错误提示问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 21:42:34