Declaring UMD modules

UMD stands for Universal Module Definition. Just like in the case of AMD and CommonJS modules we should avoid using UMD at design time and leave its generation to the TypeScript compiler. UMD modules usually support bow AMD and CommonJS module loaders and bundles but some implementations (Like the Browserify stand alone mode) also support the usage of an UMD module as a global variable.

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

If we have an ES6 module like the following one:

import { IArrays } from '../../interfaces';

class Arrays implements IArrays {
  // …
}

export default new Arrays();

We can compile the preceding into an UMD module using the module compilation flag as we can see in the following Gulp task:

gulp.task('build-es6-to-commonjs', function () {
    const tsProject = ts.createProject('tsconfig.json', {
        typescript: require('typescript'),
        module: 'commonjs'
    });

    const input = './src/module_definitions/design_time/external/es6/*.ts';
    const output = './src/module_definitions/run_time/external/commonjs/';

    return gulp.src(input)
        .pipe(tsProject())
        .pipe(gulp.dest(output));
});

Note that the paths in the preceding Gulp tasks are the ones used in the companion source code. The ES6 modules are located un the the following module:

/src/module_definitions/design_time/external/es6/

The resulting UMD modules are located under the following folder:

/src/module_definitions/run_time/external/umd/

How it works

After compiling our ES6 module into JavaScript, the resulting AMD module will look 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"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {value: true});
    var Arrays = (function () {
        /// ...
    })();

    exports.default = new Arrays();
});

As we can see UMD modules are a mix between AMD a CommonJS modules. UMD module check if some objects are defined in the global scope to try to determine if the application is being used with a AMD module loader or a CommonJS loader and use the import and export methods accordingly.

Source Code

Declaring UMD modules

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.


https://www.shivkushwaha.com

Shiv Kushwaha

Author/Programmer