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.tsis in thesrcdirectory, yourtsconfig.json'sincludearray 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
includearray 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
globalssection to tellts-jestto 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-jestversion 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-jestto bridge the gap:npm install --save-dev tsconfig-paths-jest - Update your
jest.config.jsto 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.tsfile in your root with:import 'tsconfig-paths/register';
4. Ensure
相关产品推荐
相关产品推荐

