Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a node.js library lib written in ES6 (compiled with Babel) in which I export the following submodules:

"use strict";  import * as _config from './config'; import * as _db from './db'; import * as _storage from './storage';  export var config = _config; export var db = _db; export var storage = _storage; 

If from my main project I include the library like this

import * as lib from 'lib'; console.log(lib); 

I can see the proper output and it work as expected { config: ... }. However, if I try to include the library like this:

import lib from 'lib'; console.log(lib); 

it will be undefined.

Can someone explain what is happening here? Aren't the two import methods supposed to be equivalent? If not, what difference am I missing?

like image 628
left4bread Avatar asked Jul 13 '15 14:07

left4bread


People also ask

What is the difference between require X and ES6 import X in node JS?

Require is Non-lexical, it stays where they have put the file. Import is lexical, it gets sorted to the top of the file. It can be called at any time and place in the program. It can't be called conditionally, it always run in the beginning of the file.

What is the difference between import and require in JavaScript?

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .

What is the difference between ES6 and node JS?

nodejs is a javascript runtime environment, built upon Chrome's V8 engine. It understand modern javascript natively. babel is a polyfill library that allow older browsers (or even older version of nodejs) to run modern javascript syntax (ES6) by "translating" newer syntax into their older equivalent.

What is import and export in ES6?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.


1 Answers

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 }; 
like image 134
loganfsmyth Avatar answered Oct 09 '22 09:10

loganfsmyth