Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  199] [ 7]  / answers: 1 / hits: 24720  / 9 Years ago, thu, october 15, 2015, 12:00:00

I'm stuck on a problem in a react-native project. I'm trying to do a general require file, where I export all my modules. After that I would like to require only my require.js file to avoid calls like this require('../../ModuleName') in every file.



I have 4 files:



index.ios.js
/app/home.js
/app/MyView.js
/app/require.js


require.js:



module.exports = {

Home: require('./home'),
MyView: require('./MyView')

}


in index.ios.js (he modules Home and MyView are getting importet correctly)



'use strict';

var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
} = React;

var {
Home,
MyView
} = require('./app/require');

class Test_require extends React.Component {

render() {

return(
<Home />
);
}

}



AppRegistry.registerComponent('Test_require', () => Test_require);


Home.js (the module MyView is not getting importet)



'use strict';

var React = require('react-native');

var {
View,
Text
} = React;

var {
MyView
} = require('./require');

class Home extends React.Component {

render() {
console.log(MyView);
return(
<MyView />
);
}

}

module.exports = Home;


In the Home.js the MyView variable is undefined. If I want to require a module in a Module, that gets already imported in another file, the variable is undefined.



Do you guys have any clue why I can do this or is there a better solution for my problem? Thanks for any clue


More From » ios

 Answers
12

So I'm posting my own answer in case someone else has the same problem.



In a syntax like this the required files are getting loaded synchronously. So if the component's build is faster than requiring files, this problem happens. Either make your components load lazy when you need them or use es6 import syntax like this (import loads asynchronously):



import React from 'react-native'


cheers!


[#64730] Tuesday, October 13, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kurtisl

Total Points: 559
Total Questions: 110
Total Answers: 97

Location: Tokelau
Member since Sun, May 7, 2023
1 Year ago
;