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

如何在React Native中调试本地依赖的src目录TypeScript文件?

调试React Native本地依赖的TypeScript源码步骤

1. 确保本地依赖生成正确的Source Map

  • 编辑依赖库的tsconfig.json,开启Source Map生成:
    {
      "compilerOptions": {
        "sourceMap": true,
        // 保留其他原有配置
      }
    }
    
  • 若依赖使用Babel编译,在babel.config.js中启用Source Map:
    module.exports = {
      presets: [
        ['module:metro-react-native-babel-preset', { sourceMaps: 'both' }]
      ]
    };
    
  • 重新构建依赖,确认dist目录下生成与编译后JS文件同名的.map文件。

2. 配置React Native项目优先解析依赖源码

修改项目根目录的metro.config.js,让Metro直接加载依赖的src目录而非编译后的dist:

const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
const path = require('path');

const customConfig = {
  resolver: {
    resolveRequest: (context, moduleName, platform) => {
      // 替换为你的本地依赖包名
      if (moduleName === 'your-local-lib-name') {
        return {
          filePath: path.resolve(__dirname, '../path-to-your-local-lib/src/index.ts'),
          type: 'sourceFile',
        };
      }
      return context.resolveRequest(context, moduleName, platform);
    },
  },
};

module.exports = mergeConfig(getDefaultConfig(__dirname), customConfig);

3. 调试器端配置

  • Chrome调试:打开Chrome DevTools的Sources面板,在webpack://或Metro对应的源路径下找到依赖的src文件,直接设置断点。
  • WebStorm调试:
    1. 将本地依赖的src目录添加为项目Content Root(右键目录 → Add Content Root)。
    2. 在Run/Debug配置中选择React Native调试项,确保勾选Enable JavaScript debugger。
    3. 直接在src文件中设置断点,启动调试会话。

4. 清除缓存并重启服务

执行命令清除Metro缓存,确保配置生效:

npx react-native start --reset-cache

重新启动React Native应用和调试会话。

内容的提问来源于stack exchange,提问作者Saira Nawaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:10:32