Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use "import * as Foo" versus "import Foo"? [duplicate]

Tags:

I'm converting a BackboneJS (v1.2.2) project to ES6 w/ BabelJS.

I noted that there's a difference between:

import Backbone from 'backbone' 

and

import * as Backbone from 'backbone' 

After reading here I understand that the former is importing the default export of Backbone where as the latter allows me to "import the whole module and refer to its named exports via property notation."

I'm struggling to understand the difference between these. Objects are returned in both instances, but the former appears to be decorated with additional properties/methods. At the very least I would presume importing "the whole module" would have more properties/methods... but I'm seeing the opposite.

like image 886
Sean Anderson Avatar asked Aug 26 '15 20:08

Sean Anderson


People also ask

Why import * is not recommended?

Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import.

What does from file import * do?

It just means that you import all(methods, variables,...) in a way so you don't need to prefix them when using them.

What happens if I import the same module twice?

The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.


1 Answers

a module can export a single "default export" and / or one or more named exports.

Importing with the first syntax in your question only imports the default export, and sets a named identifier (Backbone in your sample) to that object.

The second syntax is known as a namespace import, and it imports the whole module under a single "namespace" object.

For example:

export.js

let b = {b: 2}; export default {a: 1}; // <- this is the ONLY default export export {b}; export let c = {c: 3}; 

import.js

import SomeName from 'export'; // 'SomeName' is now the {a: 1} instance. import {b} from 'export'; // 'b' is now the {b: 2} instance. import * as ns from 'export'; /* 'ns' now has properties 'default', 'b' & 'c',   representing {a: 1}, {b: 2} & {c: 3} respectively */ 
like image 172
Amit Avatar answered Oct 07 '22 05:10

Amit