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?
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.
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 .
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.
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.
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With