Tags: Node.JS »»»» JavaScript
ES6 modules are a cool new feature coming with Node.js 10.x, and a pre-release version available is avaible in 9.x. ES6 modules implement most of what we can do with Node.js's traditional CommonJS modules. One feature missing is the ability to dynamically select the module to load. The ES6 import
statement only takes a static string. A new feature, landing in Node.js 9.7.x, adds an import()
function offering a new way to load modules.
The most important feature may be that import()
can be used in a CommonJS module to import an ES6 module.
UPDATE Jan 21, 2020: It is almost two years later and Node.js 14.x is getting close to release, and among the features is first class support for ES6 modules. This blog post has been updated. See: Using Dynamic import in Node.js lets us import ES6 modules in CommonJS code, and more - UPDATED /UPDATE
I am not clear on the general use-case targeted by the Dynamic Import feature. But I do have two specific instances demonstrating rationales for using import()
. Namely:
- Dynamically determining the module to load at run time
- Loading an ES6 module into a Node.js/CommonJS module
As of this writing, Node.js 9.7, using ES6 modules and using import()
requires running node
with the --experimental-modules
flag.
Loading an ES6 module in a Node.js/CommonJS module
A few days ago I wrote about the @std/esm
module which enables loading an ES6 module in a CommonJS module using the require()
function. That process required replacing the require()
function with one created by @std/esm
. Replacing a standard platform function is never a preferable thing to do.
With the new Dynamic Import feature there's another route, because import()
is available in both ES6 module and CommonJS module contexts. This new function is an API which can import ES6 modules. Because loading an ES6 module is an asynchronous process, import()
returns a Promise. Therefore it's not a direct replacement of the require()
function we're familiar with.
Consider a simple ES6 module:
$ cat cjs.js
export default function() {
console.log('Hello World from ES6 module');
}
This is easy to use from another ES6 module: import t from 't';
But by the rules of what modules can be loaded where, the big gap was using ES6 modules in a CommonJS module.
Consider:
$ cat cjs.js
const util = require('util');
import('./t.mjs')
.then(t => {
console.log(util.inspect(t));
t.default();
})
.catch(err => {
console.error(err);
});
When run we get the following output:
$ node --version
v9.7.0
$ node --experimental-modules cjs.js
(node:10282) ExperimentalWarning: The ESM module loader is experimental.
{ default: [Function: default] }
Hello World from ES6 module
The first thing we learn is that indeed import()
is a function returning a Promise. The result of the Promise is the loaded module.
That loaded module object is an anonymous object containing the items exported by the module. We can see this more clearly by adding another item to t.mjs
:
$ cat t.mjs
export default function() {
console.log('Hello World from ES6 module');
}
export const meaning = 42;
Then rerunning the app:
$ node --experimental-modules cjs.js
(node:16121) ExperimentalWarning: The ESM module loader is experimental.
{ default: [Function: default], meaning: 42 }
Hello World from ES6 module
We see the new field showed up in the ES6 module object.
We won't be able to use this as a direct replacement for require()
because the global context doesn't support await
on a Promise:
$ cat bad.js
const util = require('util');
const t = await import('./t.mjs');
console.log(util.inspect(t));
t.default();
We expect this to fail because await
can only be used inside an async function. When run this fails as expected:
$ node --experimental-modules bad.js
(node:17135) ExperimentalWarning: The ESM module loader is experimental.
/home/david/t/bad.js:3
const t = await import('./t.mjs');
^^^^^
SyntaxError: await is only valid in async function
at new Script (vm.js:51:7)
at createScript (vm.js:136:10)
at Object.runInThisContext (vm.js:197:10)
at Module._compile (module.js:626:28)
at Object.Module._extensions..js (module.js:673:10)
at Module.load (module.js:575:32)
at tryModuleLoad (module.js:515:12)
at Function.Module._load (module.js:507:3)
at createDynamicModule (internal/loader/Translators.js:50:15)
at setExecutor (internal/loader/CreateDynamicModule.js:49:23)
While that doesn't work, we can use import()
in other contexts such as inside an async function. See the next section for an example.
Dynamically determining the ES6 module to load at runtime
My book Node.js Web Development, 4th edition, is nearing completion (meaning I'm working hard on editing the book as we speak). The book demonstrates building Node.js app's by walking the reader through building a simple application that stores data in a database. In the 4th edition I'm updating the book to use async functions and ES6 modules.
As demonstration app, it's desired to show how to use several kinds of databases to store data. The cleanest architectural choice is to define an API to be implemented by the several modules that will interface with each database, and we end up with this list of modules:
notes-memory.mjs
notes-fs.mjs
notes-level.mjs
notes-sqlite3.mjs
notes-sequelize.mjs
notes-mongodb.mjs
It should be obvious - each of these modules deal with storing "notes" in the corresponding database system.
The rest of the application needs a simple method to dynamically choose between these modules.
In the 3rd edition, this is the method used:
const notes = require(process.env.NOTES_MODEL
? path.join('..', process.env.NOTES_MODEL)
: '../models/notes-memory');
That was pretty simple but it doesn't work with ES6 modules. As I said above, the ES6 import
statement only takes a simple string literal. Meaning you cannot do this:
import notes from process.env.NOTES_MODEL
? path.join('..', process.env.NOTES_MODEL)
: '../models/notes-memory';
For the 4th edition the chosen approach is to use the dynamic import()
function. This is not a statement, but a function which returns a Promise that, when resolved, is the module.
This won't work as a top-level code snippet to dynamically choose the module to load:
const notes = await import(process.env.NOTES_MODEL
? path.join('..', process.env.NOTES_MODEL)
: '../models/notes-memory');
That's because await
only works inside an async
function, and this is outside any function.
What I ended up implementing is this module, called notes.mjs
, that will delegate to the dynamically chosen module based on an environment variable.
var NotesModule;
async function model() {
if (NotesModule) return NotesModule;
NotesModule = await import(`../models/notes-${process.env.NOTES_MODEL}`);
return NotesModule;
}
export async function create(key, title, body) { return (await model()).create(key, title, body); }
export async function update(key, title, body) { return (await model()).update(key, title, body); }
export async function read(key) { return (await model()).read(key); }
export async function destroy(key) { return (await model()).destroy(key); }
export async function keylist() { return (await model()).keylist(); }
export async function count() { return (await model()).count(); }
export async function close() { return (await model()).close(); }
The functions at the bottom match the API supported by these modules.
What's happening is that model()
either immediately returns the module object (if it's already been loaded) or uses import()
to load the module. We have to use await
because import()
itself returns a Promise.
In the API delegation methods we have to use (await model())
because model
is an async function, and therefore returns a Promise.
You may be thinking (because I am) what's the impact of this layer of indirection? There's several await
and async
operations going on, shouldn't this be a burden?
The first time through is where the big execution cost occurs. That's because of the time required to load the module.
On subsequent times through, the module will have been loaded and model()
immediately returns a resolved Promise. It's fast to construct a resolved Promise, and it's fast to retrieve its value. Therefore the cost is constructing a Promise object then retrieving the resolved value, which sure adds a little bit of overhead but it's minor.