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

后端 未结 3 1021
闹比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: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.

提交回复
热议问题