What is the difference between import * as react from 'react' vs import react from 'react'

后端 未结 3 1006
闹比i
闹比i 2020-12-17 10:06

I am new to React or the coding background in general. And I am not sure what is the difference between the statements

import * as react from \'react\'


        
相关标签:
3条回答
  • 2020-12-17 10:40

    There are 3 types of most import commonly used imports.

    Type 1

    import * as A from 'abc';
    

    This will import everything which is marked as export in abc. You can access them using below code.

    A.Component 
    

    Type 2

    import {A} from 'abc';
    

    This will import A from abc, containing something like this:

    export const A = () => {};
    

    Type 3

    import A from 'abc';
    

    This will import the default export from abc as A. The export can look like this:

    const B = () => {}; // The name "B" is not exported, only the value.
    
    export default B;  // at the end of component
    
    0 讨论(0)
  • 2020-12-17 10:42

    Pattern import * as React from 'react is related to the use of type systems in React like Flow or Typescript. Using import React from 'react' has led to issues with importing types definitions. For now in Typescript you can use allowSyntheticDefaultImports flag, which resolves this issue and imports all types even if you use import React from 'react'.

    0 讨论(0)
  • 2020-12-17 10:44

    In general, for ES2015 (ES6) modules

    import * as name from 'module';
    

    is a namepace import that indicates that all exported objects are to be placed in the name namespace. You can then do:

    name.blabla1
    name.blabla2
    etc ...
    

    The namespace is not callable. So you cannot do:

    name();
    

    While:

    import name from 'module';
    

    is a default import that is equivalent to:

    import {default as name} from 'module';
    

    You're importing only the default object from the module.

    In the case of React, the confusion maybe/probably arises from the fact that React's default export is ... React (Babel adds the default export for interoperability reasons). Strictly speaking, the syntax to use is:

    import * as React from 'react';
    

    or

    import {Whatever} from 'react';
    

    The following work only because of the transformation by Babel (not 100% sure):

    import React from 'react';
    import React, { Whatever } from 'react';
    

    For those using TypeScript, prior to version 2.7, the default was to treat:

    import * as name from 'module';
    

    as being equivalent to:

    const name = require('module');
    

    and:

    import name from 'module';
    

    as being equivalent to:

    const name = require('module').default;
    

    Since version 2.7, if your compiler settings specify "esModuleInterop" to true (which is recommended), then you can use the ES2015 syntax behavior.

    0 讨论(0)
提交回复
热议问题