typescriptvuejs3vitevitest

Vitest - @ src folder alias not resolved in test files


I have a vue3 project using Vite/Vitest, as recommanded in Vue.js documentation.

Here is the structure of the project:

src
  components
    // my Vue components here, potentially in sub-folders. For example:
    HelloWorld.vue 
  router
    index.ts
  App.vue
  main.ts
vitest
  components
    // My test specs. For example:
    HelloWorld.spec.ts
// ...
tsconfig.app.json
tsconfig.json
tsconfig.vite-config.json
tsconfig.vitest.json
vite.config.ts

The @/ alias for src folder is resolved properly in components files. However, in my test files, I get an error: cannot find module.

For example, in HelloWorld.spec.ts:

import HelloWorld from '@/components/HelloWorld.vue'; // <-- error !
import { describe, it } from 'vitest';

describe('HelloWorld', () => {
  it('should day hello', () => {
    // ...
  });
});

tsconfig.app.json

{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": [
    "env.d.ts",
    "src/**/*",
    "src/**/*.vue"
  ],
  "exclude": [
    "vitest/**/*"
  ],
  "compilerOptions": {
    "composite": true,
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./src/*"
      ]
    },
    "strict": true,
    "experimentalDecorators": true
  }
}

vite.config.js

import vue from '@vitejs/plugin-vue';
import { fileURLToPath, URL } from 'url';
import { defineConfig } from 'vite';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  test: {
    include: ['./vitest/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
  },
});

Solution

  • The final solution that worked for me was to include the test files in tsconfig.vitest.json:

    tsconfig.app.json (unchanged from question post)

    {
      "extends": "@vue/tsconfig/tsconfig.web.json",
      "include": [
        "env.d.ts",
        "src/**/*",
        "src/**/*.vue"
      ],
      "exclude": [
        "vitest/**/*"
      ],
      "compilerOptions": {
        "composite": true,
        "baseUrl": ".",
        "paths": {
          "@/*": [
            "./src/*"
          ]
        },
        "strict": true,
        "experimentalDecorators": true
      }
    }
    

    tsconfig.vitest.json

    {
      "extends": "./tsconfig.app.json",
      "include": [
        "vitest/**/*",
      ],
      "exclude": [],
      "compilerOptions": {
        "composite": true,
        "lib": [],
        "types": [
          "node",
          "jsdom"
        ],
      }
    }