如何让 vitest 读取我的绝对导入?

问题描述 投票:0回答:1

我正在从 CRA 迁移到 Vite,但在尝试让我的测试再次运行时遇到问题。

我的导入看起来像这样:

import { ComponentA } from 'components/ComponentA';
import { ComponentB } from 'components'; // has an index file

import { utilA } from 'utilities';

import { staticData } from 'components/staticData/data';

在我的迁移中(以及我之前使用 CRA 进行的迁移),我模仿了 CRA 文档中的绝对导入设置:https://create-react-app.dev/docs/importing-a-component/#absolute -进口

我已经用我的

tsconfig.json
设置了:

{
  "compilerOptions": {
    "target": "ESNext",
    "baseUrl": "src",
    "module": "esnext",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "noImplicitAny": false,
    "typeRoots": ["./@types"],
    "noFallthroughCasesInSwitch": true,
    "rootDirs": ["./bin"]
  },
  "include": ["src"]
}

值得注意的是,我遵循其文档中的

baseUrl
include: ["src"]
字段。我也设置了我的
vite-config.ts
:

/// <reference types="vitest" />

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import viteTsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig(() => {
  return {
    server: {
      open: true,
    },
    plugins: [react(), viteTsconfigPaths()],
  };
});

它有效,并且我的应用程序正在构建和渲染良好,但是,当我尝试使用

vitest
运行测试时,它给我的一些导入带来了
undefined
错误。这是输出:

test output

以及错误所在:

import { ArelFilterInputTypes, IArelFilterColumnConfig } from 'components/filter';

console.log(ArelFilterInputTypes);

当我运行测试时,这显示为输出:

console output

我尝试过的事情

我最初尝试将

alias
paths
添加到我的
vite-config
tsconfig.json
:

// tsconfig
"paths": {
  "components/*": ["components/*"]
}
alias: {
  components: path.resolve(__dirname, './src/components'),
},

但这不起作用。我不完全确定 vitest 的问题出在哪里。有人可以帮助我吗?

reactjs typescript create-react-app vite vitest
1个回答
0
投票

问题解决了吗?我也有一样的

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.