Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6: "import * as alias" vs "import alias"

Is there any difference between:

import utils from 'utils'

and

import * as utils from 'utils'?

In case A:

//utils.js export function doSomething() { //... } 

In case B:

//utils.js export function doSomething() { //... } export default function doSomethingDefault() { //... } 

UPDATE:

I was mislead by intellisense feature of vscode, but as recommended a small test on node+babel showed the difference:

//index.js import utilsCaseA from './utils1' import * as utilsCaseAWildcard from './utils1' var utilsCaseARequire = require('./utils1')  import utilsCaseB from './utils2' import * as utilsCaseBWildcard from './utils2' var utilsCaseBRequire = require('./utils2')  var compareObjects =  {     utilsCaseA, utilsCaseAWildcard, utilsCaseARequire,utilsCaseB,utilsCaseBWildcard,utilsCaseBRequire }; console.log(compareObjects); 

enter image description here

like image 675
Philipp Munin Avatar asked Aug 15 '17 16:08

Philipp Munin


People also ask

What is import * as in JS?

The import * as name syntax imports all exported content of a javascript file. For example, if you want to import an entire module's contents, then access the doAllTheAmazingThings() function import * as myModule from '/modules/my-module.js'; myModule. doAllTheAmazingThings(); From the docs.

What is an import alias?

Import aliases are where you take your standard import, but instead of using a pre-defined name by the exporting module, you use a name that is defined in the importing module.

Is ES6 import asynchronous?

ES6 module loaders will be asynchronous while node.

What is default import in Javascript?

First, default imports are nameless.


1 Answers

From your example:

Case A:

//utils.js export function doSomething() { //... } 

Case B:

//utils.js export function doSomething() { //... } export default function doSomethingDefault() { //... } 

Result:

import utils from 'utils' utils() // (Case A: undefined, Case B: doSomethingDefault)  import * as utils from 'utils' utils // (Case A: utils = { doSomething: function }, Case B: utils = { doSomething: function, default: function })  import { doSomething } from 'utils' doSomething() // (both Case A and Case B: doSomething = doSomething) 

The difference between Case A and Case B is that, in Case A import utils from 'utils', utils will be undefined because there is no default export. In case B, utils will refer to doSomethingDefault.

With import * as utils from 'utils', in Case A utils will have one method (doSomething), while in Case B utils will have two methods (doSomething and default).

like image 82
inostia Avatar answered Sep 22 '22 02:09

inostia