Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require() not working with variable - react native

I meet a weird problem. If I set a variable direclty with a value like this "const myString = 'someWord';" that work but if I take the value from a variable like this "const myString = someVariable;", that doesn't work, and if I set the value on a conditional block that doesn't work too.

So, work:

    var jsonName = 'tramwayen';
    const pathex = require('../assets/JSON/' + jsonName);
    var json = JSON.parse(JSON.stringify(pathex));

doesn't work:

    var jsonName = variable;
    const pathex = require('../assets/JSON/' + jsonName);
    var json = JSON.parse(JSON.stringify(pathex));

doesn't work:

    var jsonName = '';
    if (condition) {
       jsonName = 'tramwayen';
    }
    const pathex = require('../assets/JSON/' + jsonName);
    var json = JSON.parse(JSON.stringify(pathex));

I really don't understand.

I have this error : "Invalid call at line 41: require('../assets/JSON/' + jsonName2)"

like image 993
jolearn Avatar asked Oct 14 '25 18:10

jolearn


1 Answers

Most JS bundlers cannot handle dynamic require imports. You might want to load all of the files, and put them in an object:

let data = {
    tramwayen: require('../assets/JSON/tramwayen.json'),
    something: require('../assets/JSON/something.json'),
    // and so on
};

And use the data object to retrieve the data you need.

like image 55
Tim VN Avatar answered Oct 17 '25 13:10

Tim VN