找不到模块'./public/icons/icon.svg'或其相应的类型声明,测试仅在Github Action中失败

him*_*mip 2 github reactjs next.js github-actions

我的 Next.js React 应用程序测试在本地通过,但在 Github Actions 中失败。

next.config.js这个导出来了解svg导入:

module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/i,
      issuer: /\.[jt]sx?$/,
      use: ['@svgr/webpack'],
    });

    return config;
  },
};
Run Code Online (Sandbox Code Playgroud)

然后我得到了一些 SVG 图标,并将它们导入到应用程序中,如下所示:

import StatusMessageErrorIcon from '../../../public/icons/Status-message-error.svg';

<StatusMessageErrorIcon fill="red" width="18" height="18" />
Run Code Online (Sandbox Code Playgroud)

一切正常,图标显示。

然后我进行了一个测试,用该图标呈现页面,render(<Create />);

测试在本地运行,一切通过。

但在 Github Action 中运行测试失败,并显示:

Test suite failed to run

src/MyForm.tsx:11:36 - error TS2307: Cannot find module '../../../public/icons/Status-message-error.svg' or its corresponding type declarations.

11 import StatusMessageErrorIcon from '../../../public/icons/Status-message-error.svg';
Run Code Online (Sandbox Code Playgroud)

Github Action 非常基本:

steps:
  - uses: actions/checkout@v3

  - name: Use Node.js ${{ matrix.node-version }}
    uses: actions/setup-node@v3
    with:
      node-version: ${{ matrix.node-version }}
      cache: 'npm'

  - name: Install npm packages
    run: npm ci

  - name: Run tests
    run: npm run test
Run Code Online (Sandbox Code Playgroud)

我不明白,有什么想法吗?

him*_*mip 5

是的,就我而言,它与 Typescript 和将 SVG 导入文件有关.tsx

如果其他人也遇到此问题,请参阅以下解决方法。

创建一个custom.d.ts包含以下内容的文件(在根级别即可):

declare module '*.svg' {
  const content: any;
  export default content;
}

Run Code Online (Sandbox Code Playgroud)

然后将此tsconfig.json文件添加到include数组中,如下所示:

declare module '*.svg' {
  const content: any;
  export default content;
}

Run Code Online (Sandbox Code Playgroud)