4.10 Importing AMD modules

In the preceding recipe we learned that we can use the function named define to declare AMD modules in this recipe we are going to learn how we can use a function named require to import AMD modules.

Getting Ready

All you need to implement in this recipe is an installation of TypeScript 2.0 or higher.

How to do it

We can import a AMD module using a function named require:

require(['ndrscr', 'jquery'], function(_, $) {

  // Using Array module
  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);

  ///…
  
});

How it works

This function is defined by the AMD module loader and takes two arguments:

  • An array which contains the list of files that we wish to import.
  • A callback function which is invoked when all the dependencies have been loaded. As we can see in the preceding code snippet, we can change the name of the modules when they are passed to the callback function. For example, we changed ndrscr to _ and jquery to $. Remember that the define function is also able to import dependencies. Some developers wonder whether they should use require or define. In a real world application, the root module uses the require function and the rest of the modules use define function.

There’s more

It is also possible to conditionally import modules but you should try to avoid this as much as you can because it creates some problems with AMD module bundlers and is considered a bad practice:

require(['require', 'ndrscr'], function(require, _) {

  if(typeof $ === 'undefined') {
    const $ = require('jquery');
  }

  // ...
  
});

The best way to handle optional dependencies is via the AMD module loader configuration. We will learn more about it later in this chapter in the recipe about RequireJS.

See also

Please refer to the recipes about the declaration of AMD modules and RequireJS in this chapter to learn more about AMD modules.


Shiv Kushwaha

Author/Programmer