This question already has an answer here:
-
Difference between import X and import * as X in node.js (ES6 / Babel)?
3 answers
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.
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 */
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
export default {
one: "One",
two: "Two",
three: "Three",
};
export var a;
importer.js
// Has 3 props ['one', 'two', 'three']
import defaultExport from 'exporter';
// Has 2 props ['default', 'a'].
import * as allExports from 'exporter';