Difference between import X and import * as X in node.js (ES6 / Babel)?

import X from Y; is a syntax sugar.

import lib from 'lib';

is equal to

import { default as lib } from 'lib';


Just adding to Logan's solution because understanding import with brackets, * and without solved a problem for me.

import * as lib from 'lib';

is the equivalent of:

import {config, db, storage} as lib from 'lib';

Where the * is similar to a wildcard that imports all of the export var from lib.

export var config;
export var db;
export var storage;

Alternatively, using:

import lib from 'lib';

Allows you to only access the default export:

// lib.js
export default storage;

Using {} also only imports specific components from the module, which reduces the footprint with bundlers like Webpack.

While:

import storage, { config, db } from './lib'

would import all modules including export default storage;

See Dan Abramov's answer: When should I use curly braces for ES6 import?


import * as lib from 'lib';

is asking for an object with all of the named exports of 'lib'.


export var config = _config;
export var db = _db;
export var storage = _storage;

are named exports, which is why you end up with an object like you did.


import lib from 'lib';

is asking for the default export of lib.


e.g.

export default 4;

would make lib === 4. It does not fetch the named exports. To get an object from the default export, you'd have to explicitly do

export default {
  config: _config,
  db: _db,
  storage: _storage
};