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

React JS中无法调用React Native共享代码的问题排查

解决React JS项目中Git子模块路径解析错误的方案

1. 修正导入路径

先确认Git子模块的实际存放位置:

  • 执行git submodule status命令,查看子模块的本地路径,比如输出类似 5f9b3d4 rn_sharecodecommon (v1.0.0-1-g5f9b3d4),说明子模块在项目根目录(/Volumes/Data/WebProject/SSCode/sharecode/)下的rn_sharecodecommon文件夹。
  • 你的App.js位于/Volumes/Data/WebProject/SSCode/sharecode/src,正确的导入路径需要相对于App.js指向子模块:
    import {getUserData} from '../../rn_sharecodecommon/Service/api'
    
    (注:../../从src目录回到项目根目录,再进入子模块文件夹)

2. 确保项目支持TypeScript文件解析

共享模块使用了.ts文件,React JS项目默认可能未配置TypeScript支持:

  • 如果不需要TypeScript,将共享模块中的api.ts重命名为api.js,同时更新导入路径。
  • 如果需要保留TypeScript,执行以下步骤:
    1. 安装TypeScript相关依赖:
      npm install typescript @types/react @types/react-dom --save-dev
      
    2. 在项目根目录创建tsconfig.json,基础配置示例:
      {
        "compilerOptions": {
          "target": "es5",
          "lib": ["dom", "dom.iterable", "esnext"],
          "allowJs": true,
          "skipLibCheck": true,
          "esModuleInterop": true,
          "allowSyntheticDefaultImports": true,
          "strict": true,
          "forceConsistentCasingInFileNames": true,
          "noFallthroughCasesInSwitch": true,
          "module": "esnext",
          "moduleResolution": "node",
          "resolveJsonModule": true,
          "isolatedModules": true,
          "noEmit": true,
          "jsx": "react-jsx"
        },
        "include": ["src", "rn_sharecodecommon"]
      }
      
    3. 重启开发服务器,让配置生效。

3. (可选)配置路径别名优化导入

为避免复杂的相对路径,可在配置文件中设置路径别名:

  • 在tsconfig.json或jsconfig.json的compilerOptions中添加:
    "baseUrl": ".",
    "paths": {
      "@shared/*": ["rn_sharecodecommon/*"]
    }
    
  • 之后导入可简化为:
    import {getUserData} from '@shared/Service/api'
    
  • 若使用Create React App且未 eject,需安装craco覆盖webpack配置,在craco.config.js中添加:
    const path = require('path');
    
    module.exports = {
      webpack: {
        alias: {
          '@shared': path.resolve(__dirname, 'rn_sharecodecommon')
        }
      }
    };
    

内容的提问来源于stack exchange,提问作者Harshal Kalavadiya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:40:59