React-Native(TypeScript)中fs模块无法解析问题求助
React Native 中
fs 模块报错的解决方案 核心问题
React Native 是移动端运行环境,完全不支持 Node.js 的 fs 核心模块——你之前修改 tsconfig 和 package.json 只是骗过了编辑器的语法检查,但实际运行时没有这个模块,所以才会出现运行时错误。
修复步骤
回滚无效配置
- 把 tsconfig.json 里添加的
"node"从compilerOptions.types中移除,避免编辑器继续误判环境 - 卸载不必要的
@types/node:npm uninstall @types/node --save-dev - 恢复 package.json 中之前为了兼容
fs做的修改(比如添加的browser字段或其他配置)
- 把 tsconfig.json 里添加的
替换为 React Native 专属文件操作方案
React Native 有专门的文件系统处理库,选其中一个即可:- 若用纯 React Native:安装
react-native-fs
替换代码里的npm install react-native-fsfs调用示例:// 原来的 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-systemimport * as FileSystem from 'expo-file-system'; const fileContent = await FileSystem.readAsStringAsync(FileSystem.documentDirectory + 'file.txt');
- 若用纯 React Native:安装
清理依赖并重新构建
- 删除 node_modules 和锁文件:
rm -rf node_modules package-lock.json yarn.lock - 重新安装依赖:
npm install - 重启 Metro 打包器,重新运行项目
- 删除 node_modules 和锁文件:
内容的提问来源于stack exchange,提问作者tobi
相关产品推荐
相关产品推荐

