Importing Without Bindings
Some modules may not export anything, and instead, only make modifications to objects in the global scope. Even though top-level variables, functions, and classes inside modules don’t automatically end up in the global scope, that doesn’t mean modules cannot access the global scope. The shared definitions of built-in objects such as Array
and Object
are accessible inside a module and changes to those objects will be reflected in other modules.
For instance, if you want to add a pushAll()
method to all arrays, you might define a module like this:
// module code without exports or imports
Array.prototype.pushAll = function(items) {
// items must be an array
if (!Array.isArray(items)) {
throw new TypeError("Argument must be an array.");
}
// use built-in push() and spread operator
return this.push(...items);
};
This is a valid module even though there are no exports or imports. This code can be used both as a module and a script. Since it doesn’t export anything, you can use a simplified import to execute the module code without importing any bindings:
import "./example.js";
let colors = ["red", "green", "blue"];
let items = [];
items.pushAll(colors);
This code imports and executes the module containing the pushAll()
method, so pushAll()
is added to the array prototype. That means pushAll()
is now available for use on all arrays inside of this module.
I> Imports without bindings are most likely to be used to create polyfills and shims.