typescript Vitest - @ src文件夹别名未在测试文件中解析

pvabu6sv  于 2023-01-27  发布在  TypeScript
关注(0)|答案(3)|浏览(270)

我有一个使用Vite/Vitest的vue 3项目,正如Vue.js文档中所建议的那样。
以下是该项目的结构:

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

src文件夹的@/别名在组件文件中正确解析。但是,在我的测试文件中,我得到一个错误:找不到模块。
例如,在HelloWorld.spec.ts中:

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

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

tsconfig.应用程序.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
  }
}

维生素配置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}'],
  },
});
arknldoa

arknldoa1#

您只需在vitest.config.js文件中指定别名:

import path from 'path'
import vue from '@vitejs/plugin-vue'

export default {
  plugins: [vue()],
  test: {
    globals: true,
    environment: 'jsdom',
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    },
  },
}
g6ll5ycj

g6ll5ycj2#

对于SvelteKit用户,我遇到了类似的问题,不得不将$lib添加到vitest.config.js

import { defineConfig } from 'vitest/config';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import path from 'path';

export default defineConfig({
  plugins: [svelte({ hot: !process.env.VITEST })],
  test: {
    globals: true,
    environment: 'jsdom',
  },
  resolve: {
    alias: {
      $lib: path.resolve(__dirname, './src/lib'),
    },
  },
});
rdrgkggo

rdrgkggo3#

最后一个对我有效的解决方案是在tsconfig.vitest.json中包含测试文件:

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
  }
}

ts配置维生素测试json

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

相关问题