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

本地测试React+TypeScript npm包时遭遇依赖查找失败问题求助

React本地npm包调试依赖问题解决方案

问题背景

我开发了一个基于TypeScript的React npm包react-analytics-tracker,在全新React项目中使用npm link本地调试时,出现了React钩子调用无效的错误(多实例冲突)。删除宿主项目的node_modules后,包功能能正常运行,但会抛出TypeScript错误:

src/App.tsx:2:34 - error TS2307: Cannot find module 'react' or its corresponding type declarations
import React, { useEffect } from 'react'

当前我用yarn run build配合tsc将代码构建到dist目录,不确定是否需要改用webpack,也不清楚正确的配置方式。

包代码

import React, { useEffect } from 'react'

interface AnalyticsData {
  pageViews: Record<string, number>
}

const analyticsData: AnalyticsData = {
  pageViews: {},
}

const AnalyticsTracker: React.FC = () => {
  useEffect(() => {
    const path = window.location.pathname

    // Update page view statistics
    analyticsData.pageViews[path] = (analyticsData.pageViews[path] || 0) + 1

    // You can add additional logic to track other events here

    console.log('Analytics Data:', analyticsData)
  }, [])

  return null
}

export default AnalyticsTracker

宿主项目依赖

"dependencies": {
  "@testing-library/jest-dom": "^5.17.0",
  "@testing-library/react": "^13.4.0",
  "@testing-library/user-event": "^13.5.0",
  "react": "^18.2.0",
  "react-analytics-tracker": "file:../react-analytics-tracker",
  "react-dom": "^18.2.0",
  "react-scripts": "5.0.1",
  "web-vitals": "^2.1.4"
}

解决方案

1. 修复React多实例冲突(核心问题)

npm link导致本地包和宿主项目各自加载了React实例,触发钩子调用错误。解决方法:

  • 在你的npm包的package.json中,将react和react-dom移到peerDependencies字段,声明包对React版本的依赖要求,不单独安装:
    "peerDependencies": {
      "react": "^16.8.0 || ^17 || ^18",
      "react-dom": "^16.8.0 || ^17 || ^18"
    },
    "devDependencies": {
      // 保留@types/react、@types/react-dom用于本地开发类型检查
      "@types/react": "^18.2.0",
      "@types/react-dom": "^18.2.0",
      "typescript": "^5.0.0"
    }
    
  • 移除包的dependencies中的react和react-dom,然后重新安装包的依赖:yarn install
  • 在宿主项目中,执行命令让本地包共用宿主的React实例:
    npm link ../react-analytics-tracker/node_modules/react
    

2. 优化TS构建配置(无需改用webpack)

用tsc足够完成构建,只需确保tsconfig.json配置正确:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "ESNext",
    "lib": ["DOM", "ESNext"],
    "jsx": "react-jsx", // 对应React 17+的自动JSX转换
    "declaration": true, // 生成类型声明文件,供宿主项目TS识别
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "NodeNext"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

同时在包的package.json中指定入口文件:

"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"module": "./dist/index.js"

3. 解决TypeScript类型缺失错误

  • 确保包的devDependencies中安装了@types/react和@types/react-dom
  • 宿主项目的tsconfig.json中,确保typeRoots包含默认的node_modules/@types(通常默认已配置):
    "compilerOptions": {
      "typeRoots": ["node_modules/@types"]
    }
    

内容的提问来源于stack exchange,提问作者Victor Sena de Lima Attar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:24:54