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

Vue3 + Script Setup + TypeScript 单元测试遇TS2307模块未找到错误求助

Fixing "Cannot find module '*.vue'" in Vue3 + Vite + Jest + Vue Test Utils

Let's break down why you're hitting this TS2307 error and how to fix it. The root issue is usually that Jest/ts-jest isn't properly recognizing Vue file type definitions or there's a mismatch between Vite's path alias setup and Jest's module resolution. Here's how to troubleshoot step by step:

1. Ensure TypeScript picks up your Vue type shims

Your shims-vue.d.ts is correctly structured, but let's double-check it's being included in TypeScript's compilation:

  • If your shims-vue.d.ts is in the src directory, your tsconfig.json's include array already covers it (src/**/*.d.ts), but try adding it explicitly to rule out path issues:
    "include": [
      "src/**/*.ts",
      "src/**/*.d.ts",
      "src/**/*.tsx",
      "src/**/*.vue",
      "src/shims-vue.d.ts" // Add this line
    ]
    
  • If you moved the shim file to your project root, update the include array to include "shims-vue.d.ts" directly.

2. Configure ts-jest to handle Vue files

Jest uses ts-jest for TypeScript processing, but it needs explicit config to understand Vue modules. Update your jest.config.js:

  • Add a globals section to tell ts-jest to use your TypeScript config and handle Vue transforms:
    module.exports = {
      // ... existing config
      globals: {
        'ts-jest': {
          tsconfig: 'tsconfig.json',
          isolatedModules: true, // Helps with script setup compatibility
          astTransformers: {
            before: ['@vue/vue3-jest/lib/transforms/vue-jsx']
          }
        }
      },
      // ... rest of config
    };
    
  • Verify your @vue/vue3-jest version matches your Vue 3 version: For Vue 3.2+, use @vue/vue3-jest@27+ (if using Jest 27) or @vue/vue3-jest@29+ (for Jest 29). Outdated versions often fail to parse <script setup> syntax.

3. Align path alias resolution between Vite and Jest

Your @/* alias is set up in both tsconfig.json and jest.config.js, but ts-jest might need extra help resolving these paths:

  • Install tsconfig-paths-jest to bridge the gap:
    npm install --save-dev tsconfig-paths-jest
    
  • Update your jest.config.js to use the resolver:
    module.exports = {
      // ... existing config
      resolver: 'ts-jest-resolver', // Add this line
      moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/src/$1' // Keep your existing alias
      },
      // Optional: Add a setup file to register paths
      setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
    };
    
  • Create a jest.setup.ts file in your root with:
    import 'tsconfig-paths/register';
    

4. Ensure

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:49:04