Skip to content Skip to sidebar Skip to footer

When To Use "import * As Foo" Versus "import Foo"?

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

Solution 1:

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};
exportdefault {a: 1}; // <- this is the ONLY default exportexport {b};
exportlet 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 */

Solution 2:

It depends on the interface of the module and how you want to utilize it. In the case of Backbone's npm package there isn't really a default export, so both versions should be roughly equivalent when transpiled by Babel.

At the very least I would presume importing "the whole module" would have more properties/methods

It depends what the default export is and what named exports there are. Here's an example of where that wouldn't be the case:

exporter.js

exportdefault {
  one: "One",
  two: "Two",
  three: "Three",
};

exportvar a;

importer.js

// Has 3 props ['one', 'two', 'three']import defaultExport from'exporter';

// Has 2 props ['default', 'a'].import * as allExports from'exporter';

Post a Comment for "When To Use "import * As Foo" Versus "import Foo"?"