Why is this import undefined in some cases?
I created a minimal React Native project to demonstrate the problem: https://github.com/allenhsu/ReactNativeImportTest
Try it react-native run-ios
and see the console logs.
Basically there are 4 JS file to check index.ios.js
, common/TestView.js
, common/colors.js
and common/index.js
.
As common/index.js
I re-exported TestView and colors in several ways.
In index.ios.js
I imported TestView from module common
.
In common/TestView.js
I have imported Colors from the module common
and also directly from common/colors.js
:
import {
Colors,
DefaultColors,
} from './';
import AnotherColors from './colors';
console.log('Colors out of component:');
console.log(Colors);
console.log(DefaultColors);
console.log(AnotherColors);
export default class TestView extends Component {
render() {
console.log('Colors in render:');
console.log(Colors);
console.log(DefaultColors);
console.log(AnotherColors);
return (
<View>
<Text>
I'm a test view.
</Text>
</View>
);
}
}
Output:
Colors out of component:
TestView.js:17 undefined // Colors
TestView.js:18 Object {white: "#FFFFFF", black: "#000000"} // DefaultColors
TestView.js:19 Object {white: "#FFFFFF", black: "#000000"} // AnotherColors
TestView.js:23 Colors in render:
TestView.js:24 Object {white: "#FFFFFF", black: "#000000"} // Colors
TestView.js:25 Object {white: "#FFFFFF", black: "#000000"} // DefaultColors
TestView.js:26 Object {white: "#FFFFFF", black: "#000000"} // AnotherColors
My only question is why the first one undefined
? Then imported into common/index.js
, then exported with a name Colors
.
What's even more interesting if I changed the re-export TestView
to:
export { default as TestView } from './TestView';
Second, DefaultColors
from Component will also be undefined.
UPDATE
If I do the same in index.ios.js
, all three variables are defined from the Component. So I believe it has something to do with the import pipeline common/index.js
and common/TestView.js
.
source to share
No one has answered this question yet
Check out similar questions: