Why is this import undefined in some cases?

Viewed 635

I created a minimal React Native project to demonstrate the problem: https://github.com/allenhsu/ReactNativeImportTest

Try react-native run-ios and see the console logs.

There're mainly 4 JS files to check, index.ios.js, common/TestView.js, common/colors.js and common/index.js.

In common/index.js, I re-exported TestView, and Colors in several ways.

In index.ios.js, I imported TestView from common module.

In common/TestView.js, I imported Colors from common module 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>
    );
  }
}

The output is:

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 is undefined? The one imported into common/index.js first then exported with name Colors.

What's more interesting is, if I change the re-export of TestView to:

export { default as TestView } from './TestView';

The second one, DefaultColors out of Component will also be undefined.

UPDATE

If I do the same thing in index.ios.js, all three variables are defined out of the Component. So I believe it's somehow related to the loop-imports of common/index.js and common/TestView.js.

0 Answers
Related