require.mx() is the function used to import functionality from external javascript files (replacing the older load() function). This short guide will discuss the use of require.mx() to import functionality, and the method for structuring javascript files that are intended to be imported using require.mx (i.e. how to write javascript libraries).

Using require.mx() to import functionality

const Xmath = require.mx('mxjs/base/utilities/math.js');

const foo = Xmath.log10(bar);

Above is a simple example of using a javascript library with require.mx(). A path to the javascript library is passed to the require.mx() function, which returns whatever is exported by the library. Usually this will be an object, with the library's functions, constants, etc. exposed as properties.

Writing javascript libraries for use with require.mx()

When a javascript file is loaded using require.mx(), an object named module is visible. The library exports its functionality by assigning something to the exports property of the module object. For example:

module.exports = {};

module.exports.log10 = function(value) { /* ... */ };

module.exports.FOO_CONSTANT = 13;

Compared to files imported with the load() function, module.exports is the equivalent of the final produced value. For example, consider the following library definition, which shows the export methods for both require.mx() and load().

(function() {
  "use strict";

  const lib = {};

  lib.foo = function() {
    //
  };

  module.exports = lib; // for require.mx()
  return lib; // for load()
})();

Scope

The load() method of importing code gave the imported library access to the scope that it was imported in (i.e. it could access all variables that were visible at the point of the call to load()). Though this was convenient in some situations, it is bad practice from a software engineering perspective for Various Reasons. The require.mx() method of importing code does not provide the imported code this access, so the caller must explicitly pass all variables into the library code. Most existing library code already behaved this way, so you will hopefully see little change with your use of external/library code.