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

React-Native(TypeScript)中fs模块无法解析问题求助

React Native 中 fs 模块报错的解决方案

核心问题

React Native 是移动端运行环境,完全不支持 Node.js 的 fs 核心模块——你之前修改 tsconfig 和 package.json 只是骗过了编辑器的语法检查,但实际运行时没有这个模块,所以才会出现运行时错误。

修复步骤

  1. 回滚无效配置

    • 把 tsconfig.json 里添加的 "node" 从 compilerOptions.types 中移除,避免编辑器继续误判环境
    • 卸载不必要的 @types/node:
      npm uninstall @types/node --save-dev
      
    • 恢复 package.json 中之前为了兼容 fs 做的修改(比如添加的 browser 字段或其他配置)
  2. 替换为 React Native 专属文件操作方案
    React Native 有专门的文件系统处理库,选其中一个即可:

    • 若用纯 React Native:安装 react-native-fs
      npm install react-native-fs
      
      替换代码里的 fs 调用示例:
      // 原来的 fs 读取代码
      // import fs from 'fs';
      // fs.readFile('/path/to/file', (err, data) => {});
      
      // 替换为 react-native-fs
      import RNFS from 'react-native-fs';
      RNFS.readFile(RNFS.DocumentDirectoryPath + '/file.txt')
        .then(content => console.log(content))
        .catch(err => console.error(err));
      
    • 若用 Expo:使用官方的 expo-file-system
      expo install expo-file-system
      
      替换代码示例:
      import * as FileSystem from 'expo-file-system';
      const fileContent = await FileSystem.readAsStringAsync(FileSystem.documentDirectory + 'file.txt');
      
  3. 清理依赖并重新构建

    • 删除 node_modules 和锁文件:
      rm -rf node_modules package-lock.json yarn.lock
      
    • 重新安装依赖:
      npm install
      
    • 重启 Metro 打包器,重新运行项目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:52:06