You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Create React App运行单元测试时引入TSX库模块找不到的解决求助

解决Create React App中@web3modal/ethers/react测试时模块找不到的问题

问题背景

在Create React App项目中,使用import { createWeb3Modal } from '@web3modal/ethers/react'引入模块,实际文件路径为node_modules/@web3modal/ethers/dist/types/exports/react.tsx,但执行npm run test时Jest报错找不到该模块,已安装TypeScript但问题仍存在。

解决方案

1. 验证导入路径与库的导出配置

先查看node_modules/@web3modal/ethers/package.json里的exports字段,确认./react是否被正确映射:

{
  "exports": {
    "./react": "./dist/types/exports/react.tsx"
  }
}

如果该映射不存在,说明当前库版本存在导出问题,尝试升级到最新稳定版:

npm install @web3modal/ethers@latest

2. 配置Jest解析TSX模块

Create React App的Jest默认可能未转译node_modules中的TSX文件,可通过以下方式调整:

  • 项目根目录创建jest.config.js文件,添加配置:
module.exports = {
  transform: {
    '^.+\\.(ts|tsx)$': 'ts-jest',
    '^.+\\.(js|jsx)$': 'babel-jest'
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
  moduleNameMapper: {
    '^@web3modal/ethers/react$': '@web3modal/ethers/dist/types/exports/react.tsx'
  }
};
  • 若不想eject,用react-app-rewired覆盖配置:
    1. 安装依赖:
    npm install react-app-rewired --save-dev
    
    1. 创建config-overrides.js:
    module.exports = function override(config, env) {
      if (env === 'test') {
        config.module.rules.push({
          test: /\.(ts|tsx)$/,
          include: /node_modules\/@web3modal/,
          use: 'ts-jest'
        });
        config.resolve.extensions.push('.ts', '.tsx');
      }
      return config;
    };
    
    1. 修改package.json的test脚本:
    "scripts": {
      "test": "react-app-rewired test"
    }
    

3. 临时直接导入文件路径

作为临时方案,可直接导入文件绝对路径(不推荐长期使用):

import { createWeb3Modal } from '@web3modal/ethers/dist/types/exports/react';

4. 检查TypeScript配置

确保tsconfig.json(若存在)包含以下配置,支持Jest解析TSX:

{
  "compilerOptions": {
    "jsx": "react-jsx",
    "module": "ESNext",
    "allowJs": true
  },
  "include": ["src", "node_modules/@web3modal/ethers/dist/types/exports/react.tsx"]
}

内容的提问来源于stack exchange,提问作者Prabhat kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 08:36:05