I understand that I cannot simply use fs in React Native as in Node. However, my situation is a bit different. Here’s a simple representation of my problem.
Library:
const fs = require('fs')
function f1() {
// do things with fs
}
function f2() {
// do things with pure javascript
}
The function I need is f2
. But when importing, the bundling fails:
The package at "pathtojs" attempted to import the Node standard library module "fs".
It failed because the native React runtime does not include the Node standard library.
Is there a way around this? Can I somehow ignore the import of fs library, which I do not need anyway? Or would it be impossible without modifying the library?
2
Answers
Use Conditional Imports
Modify the library if possible to conditionally require
fs
only whenf1
is used. For example:When
f2
is used in React Native,fs
won’t be imported, avoiding the issue.Your strategy to conditionally require
fs
in thef1
function works in Node.js, butfs
is not available in React Native since React Native doesn’t support Node.js built-in modules likefs
.If you’re planning to use
f2
in a React Native project, your design ensuresfs
will not be imported unlessf1
is invoked. However, invokingf1
in a React Native environment will still throw an error becausefs
is not available.for React native
react-native-fs
andexpo-file-system
(if using Expo)