Importing UMD modules

In the preceding recipe we learned how to declare UMD modules in this chapter we will learn how to import UMD modules.

Getting Ready

All you need to implement in this recipe is an installation of TypeScript 2.0 or higher, Gulp and the gulp-typescript module.

How to do it

Let’s take a look to the ES6 ndrscr module included in the companion source code:

import arrays from './arrays';
import collections from './collections';
import functions from './functions';
import objects from './objects';
import utility from './utility';

const VERSION = '1.0.0';
export { VERSION, arrays, collections, functions, objects, utility };

When compiled into an UMD module it looks as follows:

(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "./arrays", "./collections", "./functions", "./objects", "./utility"], factory);
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var _arrays = require("./arrays");
    var _collections = require("./collections");
    var _functions = require("./functions");
    var _objects = require("./objects");
    var _utility = require("./utility");
    var VERSION = '1.0.0', arrays = _arrays.default, collections = _collections.default, functions = _functions.default, objects = _objects.default, utility = _utility.default;
    exports.VERSION = VERSION;
    exports.arrays = arrays;
    exports.collections = collections;
    exports.functions = functions;
    exports.objects = objects;
    exports.utility = utility;

How it works

As we can see in the preceding code snippet, UMD modules use a function named require to import other external modules and the exports object to declare the public parts of the module being defined. This may seem identical to CommonJS modules but we need to keep in mind that if we run an UMD module in Node.js or in a website with RequireJS the internal implementations of the require function and the exports object will not be identical.

See also

Please refer to the recipes about ES6, AMD and CommonJS modules to learn about the declaration of external modules. Refer to chapter one to learn more about Gulp.

Shiv Kushwaha