Patterns for ES6 JavaScript modules - Part 4
For the last part in my series on patterns for ES6 modules, I thought I would include a pattern that uses named exports in a structure to expose only specific things. This pattern looks a little bit like the single structure export in Part 1 of this series in that it only exports specific things that are named as part of the export statement.
I use this pattern on the client side for modules containing remote functions. The example below comes from the LacesIDE in browser editor. This example is an abbreviated version of ./client/js/remote/apps.js. In this pattern, you create an export statement that lists by name all of the elements you want to expose. export { elementList }
defines exactly what is exposed by the module. In the example below, the last defined function, doSomethingElse, isn’t named in the export statement and so isn’t exposed by the module.
import {a7} from '/lib/altseven/dist/a7.js';
import {cuid} from '/lib/cuid/index.mjs';
export { create, update, read, deleteById };
const create = function( obj ){
var request;
/* */
},
read = function( obj ){
var request;
/* */
},
update = function( obj ){
var request;
/* */
},
deleteById = function( obj ){
var request;
/* */
},
doSomethingElse = function( obj ){
/* not exported */
};
The way you import elements from this module differs from the way you import the single named structure in Part 1 of the series. In this case, you can import specific functions by name, import { create, update, read, deletedById } from '/js/remote/apps.js'
. In this case, you call each of these functions directly, e.g create( obj )
.
You can also import all of the functions into a named scope, import * as apps from '/js/remote/apps.js'
. In this case, the exposed elements of the module become members of the named scope, e.g. apps.create( obj )
. I generally use this second method for importing these modules because I like the visual reminder of which module the function I am calling belongs to.