NextJS13 中的 vitest 配置错误:无法解析导入。

huangapple go评论69阅读模式
英文:

Error in vitest config with NextJS13: failed to resolve import

问题

I'm integrating vitest with a NextJS 13 app, but running into problems with a simple test run.

不确定问题出在哪里,我尝试在 vitest.config.ts 中进行一些调整,但没有运气。我尝试添加 dir 选项,修改 include 选项以从源文件中获取文件,但没有运气。

我以为可能与 tsconfig.json 文件有关,但它仍然输出错误。

这是文件的目录

这里是相关的文件:

vitest.config.ts

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

import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
    setupFiles: 'setupTests.ts',
    // dir: './src';
    // includeSource: ['src/**/*.{js,ts,tsx}'];
  },
});

tsconfig.json

{
  "compilerOptions": {
      "target": "ES2017",
      "lib": ["es6", "dom", "dom.iterable", "esnext"],
      "allowJs": true,
      "skipLibCheck": true,
      "strict": false,
      "forceConsistentCasingInFileNames": true,
      "noEmit": true,
      "esModuleInterop": true,
      "module": "ESNEXT",
      "moduleResolution": "node",
      "resolveJsonModule": true,
      "isolatedModules": true,
      "jsx": "preserve",
      "baseUrl": ".",
      "incremental": true,
      // "paths": {
      //     "src": ["./src/*"]
      // }
  },
  "exclude": ["node_modules"],
  "include": ["vitest.config.ts","**/*.ts", "**/*.tsx", "next-env.d.ts", "next.config.js"]
}

DataTable.test.tsx - src/common/components/DataTable/DataTable.test.tsx

// components

import DataTable from 'src/common/components/DataTable';

// dependencies
import {describe, it} from 'vitest';
import {screen, render} from '@testing-library/react';

describe('DataTable test', () => {

    it('render the app', () => {
        // arrange
            render(<DataTable />)
        // act
            const assetText = screen.getByText("asset")
        // assert
            // expect(assetText).toBeInTheDocument()
    })
}

DataTable component - src/common/components/DataTable/DataTable.tsx

export const DataTable = () => {

    return (
        <div>
            <h1>assets</h1>
        </div>
    );
};

Index.tsx - src/common/components/DataTable/index.tsx

import { DataTable } from 'src/common/components/DataTable/DataTable';

export default DataTable;

我对 vitest 和 nextjs 不太了解,将不胜感激您的帮助和指导。

英文:

I'm integrating vitest with a NextJS13 app, but running into problems with a simple test run.

NextJS13 中的 vitest 配置错误:无法解析导入。

Not sure what the problem is, I tried to do some tweaking with the vitest.config.ts but no luck. I tried adding the dir option, modified the include option to grab files from the source file but no luck.

I thought maybe it had to do with the tsconfig.json file, but it's still outputting the error.

This is the directory of the file

NextJS13 中的 vitest 配置错误:无法解析导入。

Here are the files in question:

vitest.config.ts

/// &lt;reference types=&quot;vitest&quot; /&gt;

import { defineConfig } from &#39;vitest/config&#39;
import react from &#39;@vitejs/plugin-react&#39;

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: &#39;jsdom&#39;,
    include: [&#39;src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}&#39;],
    setupFiles: &#39;setupTests.ts&#39;,
    // dir: &#39;./src&#39;
    // includeSource: [&#39;src/**/*.{js,ts,tsx}&#39;],
  },
});

tsconfig.json

{
&quot;compilerOptions&quot;: {
    &quot;target&quot;: &quot;ES2017&quot;,
    &quot;lib&quot;: [&quot;es6&quot;, &quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext&quot;],
    &quot;allowJs&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;strict&quot;: false,
    &quot;forceConsistentCasingInFileNames&quot;: true,
    &quot;noEmit&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;module&quot;: &quot;ESNEXT&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;resolveJsonModule&quot;: true,
    &quot;isolatedModules&quot;: true,
    &quot;jsx&quot;: &quot;preserve&quot;,
    &quot;baseUrl&quot;: &quot;.&quot;,
    &quot;incremental&quot;: true,
    // &quot;paths&quot;: {
    //     &quot;src&quot;: [&quot;./src/*&quot;]
    // }
},
&quot;exclude&quot;: [&quot;node_modules&quot;],
&quot;include&quot;: [&quot;vitest.config.ts&quot;,&quot;**/*.ts&quot;, &quot;**/*.tsx&quot;, &quot;next-env.d.ts&quot;, 
&quot;next.config.js&quot;]
}

DataTable.test.tsx - src/common/components/DataTable/DataTable.test.tsx

// components

import DataTable from &#39;src/common/components/DataTable&#39;;

// dependencies
import {describe, it} from &#39;vitest&#39;
import {screen, render} from &#39;@testing-library/react&#39;

describe(&#39;DataTable test&#39;, () =&gt; {

    it(&#39;render the app&#39;, () =&gt; {
        // arrange
            render(&lt;DataTable /&gt;)
        // act
            const assetText = screen.getByText(&quot;asset&quot;)
        // assert
            // expect(assetText).toBeInTheDocument()
    })
})

DataTable component - src/common/components/DataTable/DataTable.tsx

export const DataTable = () =&gt; {

    return (
        &lt;div&gt;
            &lt;h1&gt;assets&lt;/h1&gt;
        &lt;/div&gt;
    );
};

Index.tsx - src/common/components/DataTable/index.tsx

import { DataTable } from &#39;src/common/components/DataTable/DataTable&#39;;

export default DataTable;

I'm new to vitest and nextjs, your help/guidance will be appreciated.

答案1

得分: 5

  1. TypeScript 需要设置编译选项中的 "paths"。
  2. Vite 需要设置相同的别名。

TypeScript 中的 "paths" 编译选项需要在 "src" 键的末尾加上 /*,以便能够解析 "src" 目录下的路径(参考 tsconfig.json 文档):

{
  "compilerOptions": {
    "paths": {
      "src/*": ["./src/*"]
    }
  }
}

Vite/Vitest 也需要知道如何解析 "src/common/components/DataTable",通常可以通过 resolve.alias 设置来完成,但你也可以使用插件,比如 vite-tsconfig-paths,来根据相关的 tsconfig.json 文件中找到的路径别名来添加别名:

import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";

export default {
  plugins: [tsconfigPaths(), react()],
};
英文:

There are two things needed here to make the import DataTable from &#39;src/common/components/DataTable&#39;; import work:

  1. TypeScript needs the paths compilerOption set.
  2. Vite needs to have the same alias set.

The "paths" compilerOption in TypeScript will need a /* on the end of the "src" key to be able to resolve paths underneath the "src" directory (see tsconfig.json reference):

{
  &quot;compilerOptions&quot;: {
    &quot;paths&quot;: {
      &quot;src/*&quot;: [&quot;./src/*&quot;]
    }
  }
}

Vite/Vitest will also need to know how to resolve "src/common/components/DataTable", and that would usually be done with the resolve.alias setting, but rather than duplicating the alias here, you could also use a plugin, like vite-tsconfig-paths, to add the path aliases if finds in relevant tsconfig.json files:

import react from &quot;@vitejs/plugin-react&quot;;
import tsconfigPaths from &quot;vite-tsconfig-paths&quot;;

export default {
  plugins: [tsconfigPaths(), react()],
};

huangapple
  • 本文由 发表于 2023年2月8日 08:21:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75380295.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定