skip to Main Content

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


  1. Use Conditional Imports

    Modify the library if possible to conditionally require fs only when f1 is used. For example:

    let fs;
    
    function f1() {
      fs = require('fs'); // Import `fs` only when `f1` is called
      // do things with fs
    }
    
    function f2() {
      // do things with pure javascript
    }
    
    module.exports = { f1, f2 };
    

    When f2 is used in React Native, fs won’t be imported, avoiding the issue.


    Login or Signup to reply.
  2. Your strategy to conditionally require fs in the f1 function works in Node.js, but fs is not available in React Native since React Native doesn’t support Node.js built-in modules like fs.

    If you’re planning to use f2 in a React Native project, your design ensures fs will not be imported unless f1 is invoked. However, invoking f1 in a React Native environment will still throw an error because fs is not available.

    for React native
    react-native-fs and expo-file-system (if using Expo)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search