0

My question is about what's the difference between these two kinds of import.

import abc from ./utilities/fibo and import * as abc from ./utilities/fibo

I thought they were almost same, but it turns out something is out of my expectation.

Although I think the problem is platform agnostic, this is written in react native. Expo version 27.1.

Two simple js file:

fibo.js:

export default "string";

app.js:

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import abc from './utilities/fibonacci';

debugger // set break point here

export default class App extends React.Component {
  render() {
    return (
      <Text>{abc}</Text>
    );
  }
}

You can see that I have set break point in app.js. When I run the code, it stops at the break point. When I inspect abc then, a reference error told me that

abc is not defined

But this totally works in <Text>{abc}</Text> and it renders correctly.

If I use an alias for the imported module:

app.js:

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import * as abc from './utilities/fibonacci';

debugger // set break point here

export default class App extends React.Component {
  render() {
    return (
      <Text>{abc}</Text>
    );
  }
}

Run code again, break point meets me. Inspection of abc tells me that it is already defined as an object with a property named as 'default' whose value is 'string'.

And the difference doesn't just stop here. Resume to run the code, error jumps out:

Invariant Violation: Objects are not valid as a React child (found: object with keys {default}). If you meant to render a collection of children, use an array instead.

I have to change <Text>{abc}</Text> to <Text>{abc.default}</Text> to make things happen.

So, what is difference between them? And why?

krave
  • 1,629
  • 4
  • 17
  • 36

0 Answers0