Running UMD modules

In the preceding recipes we learned how to declare and import CommonJS modules in this chapter we will learn how to run CommonJS 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 plugin.

How to do it

Just like in the case of CommonJS modules, UMD modules can be used natively imported from a Node.js application. This is showcased in the companion source code (check out the file named umd.js under the directory named node):

const _ = require('../src/module_definitions/run_time/external/umd/ndrscr.js');

const result1 = _.arrays.first([5, 4, 3, 2, 1], 3);
console.log(result1);

const result2 = _.arrays.last([5, 4, 3, 2, 1], 3);
console.log(result2);

//...

The main advantage of UMD modules is that they can also be used in a web browser in combination with RequireJS. This means that the same module will work in both Node.js and RequireJS environments.

How it works

The companion source code showcases how we can run the UMD modules in a web browser using RequireJS just as we did previously in this chapter. The RequireJS configuration file included in the examples (check out the file named require_umd.config.js located under the /src/module_loaders/requirejs folder) looks as follows:

requirejs.config({
    baseUrl: '../../src/module_definitions/run_time/external/umd',=
    waitSeconds: 15,
    paths: {
      'jquery' : '../../../../../node_modules/jquery/dist/jquery.min'
    }
});

The configuration above is almost identical to the one that we used in the recipe about RequireJS. The only significant difference is that we have used a different base URL in order to point to the folder which contains the UMD modules. The companion source code also includes a file named requirejs_umd.html under the /browser/external folder/ this file showcases how to load the RequireJS configuration file:

<script src="../../node_modules/requirejs/require.js"></script>
<script src="../../src/module_loaders/requirejs/require_umd.config.js"></script>
<script src="../../src/module_loaders/requirejs/app.js"></script>

Source Code

Running 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