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:

  1. // module code without exports or imports
  2. Array.prototype.pushAll = function(items) {
  3. // items must be an array
  4. if (!Array.isArray(items)) {
  5. throw new TypeError("Argument must be an array.");
  6. }
  7. // use built-in push() and spread operator
  8. return this.push(...items);
  9. };

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:

  1. import "./example.js";
  2. let colors = ["red", "green", "blue"];
  3. let items = [];
  4. 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.